How to ban input of letters? - react-hook-form

How to ban letters from input react hook form?
I tried pattern, watch, setValue but didn`t get any normal result.
const {register, formState: {errors}, handleSubmit, setValue, getValues,} = useForm({
defaultValues: {
bid: 1
}
});
// some code...
<input {...register("age", {required: true, min: 1, max: 100})}
onChange={(e)=>{e.target.value.replace(/[0-9]/,'')}} type="number"/>

Related

Yup compare fields validation with react hook form

I've been using React hook form and have a compare validation written on the input itself.
I need to move over to Yup validation lib as others on the project are using it so for consistency. Here is what I currently have that is working but having problems when I use a yup.schema.
const {
register,
setValue,
getValues,
formState: { errors, isValid },
clearErrors,
trigger,
} = useForm({
mode: 'onBlur',
defaultValues: {
password: '',
compare: '',
},
})
return(
<div>
<Input
name='password'
{...register('password', { required: true })}
<Input
name='compare'
{...register('compare', {
validate: (value: string) => {
const { password} = getValues()
return password === value || ''
},
})}
</div>
)
As I said this above works but now I thought I could add a schema but that breaks all what I have so I'm trying to figure out how I can achieve this using yup schema.
const schema = yup.object().shape({
password: yup.string().required(),
compare: yup.string().test(
'compare',
(field) => {
... not sure how to compare against another filed here ?
}
),
})
const {
register,
setValue,
getValues,
formState: { errors, isValid },
clearErrors,
trigger,
} = useForm({
mode: 'onBlur',
resolver: yupResolver(schema),
defaultValues: {
password: '',
compare: '',
},
})

Select2 Rails. How to filtering special characters?

I'd like to prevent the user from placing special characters, only letters and numbers
I have the following code:
$("#js-customer").select2({
maximumSelectionLength: 12,
minimumInputLength: 1,
tags: true,
tokenSeparators: [',', ' '],
language: {
maximumSelected: function (e) {
return I18n.t('customers.alert.limit_max');
},
inputTooShort: function (e) {
return I18n.t('customers.alert.limit_min');
}
},
});
if anyone knows of any simple way to limit special characters (in the same ("#js-customer").select2) and if you could help me I would be very grateful

How to prevent select2 to call select2:close the second time when selectOnClose is set to true?

I am using Select2 V. 4.0.10
I want to have a select2 that behaves the same way when you select using the Enter key and the Tab key.
What happens is that when selecting using the Tab key, the close event is called twice, which is not what was intended to do.
var data = [
{ id: 0, text: 'New' },
{ id: 1, text: 'In Process' },
{ id: 2, text: 'Draft' },
{ id: 3, text: 'Submitted' },
{ id: 4, text: 'Deleted' }
];
$(".test").select2({
allowClear: true,
selectOnClose: true,
data: data,
placeholder: "Select a status"
});
$("select.test", "body").off("select2:close").on("select2:close", function (e){
// This is called twice
console.log("select2:close");
});
select.test {
width: 200px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<select class="test"></select>
Here are the sequences of the select2 events that are triggered when selecting with the Tab/Enter key.
TAB
select2:opening
select2:open
select2:closing
select2:selecting
change
change.select
select2:closing
select2:close
select2:select
select2:close
ENTER
select2:opening
select2:open
select2:selecting
change
change.select
select2:closing
select2:close
select2:select
As the pattern in always the same, the solution was to create a variable that would be toggled on when select2:select was triggered, and use that to see if it was be used before.
Notice, instead of using the global window object you should rather use a class variable or a prototype property to store this boolean.
var data = [
{ id: 0, text: 'enhancement' },
{ id: 1, text: 'bug' },
{ id: 2, text: 'duplicate' },
{ id: 3, text: 'invalid' },
{ id: 4, text: 'wontfix' }
];
window._select2Select = false;
$(document).on('select2:select', "select", function (e) {
window._select2Select = true;
});
$(".test").select2({
allowClear: true,
selectOnClose: true,
data: data,
placeholder: "Select a status"
});
$("select.test", "body")
.off("select2:close")
.on("select2:close", function(e) {
if(window._select2Select){
window._select2Select = false;
return;
}
console.log("select2:close");
window._select2Select = false;
});

Override Ascending Descending functions - ui-grid

I'm using grid view for my reporting view. I need to override functions on Sort Ascending and Sort Descending event.
Here is my code for gridOptions.
var dynamicColumnDefs = _.map(_.keys(res[0]), function (key) {
return {name: key, field: key, width: '10%', enableHiding: false};
});
console.log('columnDefs', dynamicColumnDefs);
scope.gridOptions = {
data: res,
enableColumnResize: true,
enableGridMenu: true,
exporterMenuPdf: false,
columnDefs: dynamicColumnDefs,
enableHorizontalScrollbar: 2,
enableVerticalScrollbar: 2,
onRegisterApi: function (gridApi) {
// I hope I need to overide my function here
}
};
I need to trigger the event once I click Ascending and Descending only. How can I do it.
Thank you
I can do that;
scope.gridOptions = {
data: res,
enableColumnResize: true,
enableGridMenu: true,
exporterMenuPdf: false,
columnDefs: dynamicColumnDefs,
enableHorizontalScrollbar: 2,
enableVerticalScrollbar: 2,
onRegisterApi: function (gridApi) {
scope.gridApi = gridApi;
scope.gridApi.core.on.sortChanged(scope, scope.sortChange);
sortChanged(scope.gridApi.grid, [scope.gridOptions.columnDefs[1]]);
}
};
sortChanged = function (grid, sortColumns) {
// Do Whatever I want
}

jqGrid boolean or enumeration dropdown filtering for columns

I'm using jqGrid to display tabular data on my first ASP.NET MVC 3 and find it really useful, particularly filtering down data. For string-type I use the column-filtering with "contains" and that works wonderfully for culling out the strings. For the date data I use the date picker. Great.
Now I've got a few columns (e.g., "Contains nuts") which are essentially boolean values. I want to provide a way to filter these. Right now they are displayed as "true" and "false" and use the same string-based filtering that my string-type columns use. That's a bit clunky. I think what I'd like to do instead is have a way to choose one of three values (true/false/both) via a dropdown mechanism.
My current colModel has an entry like so for my 'boolean' field:
{ name: 'ContainsNuts',
index: 'ContainsNuts',
align: 'left',
searchoptions: { sopt: ['eq, 'ne']}
}
which only works when the user types in 'false' or 'true' - again, clunky.
For a few other columns, I wanted to use dropdowns for enumerations, e.g., I have a 'Cones' column, since there are quite a few rows and I page the results - using the auto complete text filtering is a bit hit-or-miss for the user to find all the possible values. Hope that makes sense.
So what I've tried is this - I created a controller action that looks like so:
public JsonResult AvailableCones()
{
var context = new IceCreamEntities();
var query = context.Cones.AsQueryable().Distinct();
List<string> all = query.Select(m => m.Name).ToList();
return Json(all, JsonRequestBehavior.AllowGet);
}
And I did something like this [perhaps convoluted approach] to create a dropdown selection in the filtering dialog for Cones in my document ready:
...
createSearchSelection = function (someValues) {
var outputValues = "";
if (someValues && someValues.length) {
for (var i = 0, j = someValues.length; i < j; ++i) {
var entry = someValues[i];
if (outputValues.length > 0) {
outputValues += ";";
}
outputValues += entry + ":" + entry;
}
}
return outputValues;
}
setTheSearchSelections = function (colName, url){
$('#icecreamgrid').jqGrid('setColProp', colName,
{
stype: 'select',
searchoptions: {
value: createSearchSelection(url),
sopt: ['eq']
}
});
}
gotData = function(data) {
setTheSearchSelections('ConeType', data);
}
var url = "/IceCream/AvailableConeTypes";
$.get(url, null, gotData);
The result is that I get a drop-down for the ConeType column in the search dialog and the correct rows shows up in the column. Great. That's pretty cool that it works.
What I don't know how to do, however, is to get a dropdown to show up in my column header filter just like the one that now shows up in the filter dialog. How can I augment what I have to make this happen? Secondly, how can I make what I've got work for boolean values?
First part of your question is the displaying and filtering of the boolean values. I use checkboxes to display such values. In difference on your case I have typically many such columns. To reduce the size of the JSON data I use "1" and "0" instead of "true" and "false". Next I use the following column settings
formatter: 'checkbox', align: 'center', width: 20,
edittype: 'checkbox', editoptions: { value: "1:0" },
stype: "select", searchoptions: { sopt: ['eq', 'ne'], value: "1:Yes;0:No"
So for the searching the user have to choose "Yes" or "No" in the select box. Because I have many of such columns I defined templateCeckbox object in one JavaScript file which I include on every page of the project:
my.templateCeckbox = {
formatter: 'checkbox', align: 'center', width: 20,
edittype: 'checkbox', editoptions: { value: "1:0" },
stype: "select", searchoptions: { sopt: ['eq', 'ne'], value: "1:Ja;0:Nein" }
};
Then the typical column definition is
{
name: 'IsInBasis', index: 'InBasis', template: my.templateCeckbox,
cellattr: function () { return ' title="TS-Basis"'; }
},
(see the answer for details about the column templates). I find also practical if the tooltip shown if one hover the checkbox will be the text close to the column header. So I use cellattr attribute. In case of having many columns with the checkboxes it improves the usability a little.
To be able to display many columns with chechboxes I use personally vertical column headers. I recommend you to read the old answer which could be additionally interesting because it describes how to implement quick filtering of the data with respect of external checkbox panel.
Now about the building of the selects for the 'Cones' column. If you has AvailableCones action which provide the list of possible options like array (list) of strings you should use dataUrl:'/IceCream/AvailableConeTypes' instead of value: createSearchSelection(url) as the searchoptions. You well add only the buildSelect function which I described in "UPDATED" part of the answer.
{
name: 'ConeType', width: 117, index: 'ConeType', editable: true, align: 'center',
edittype: 'select', stype: 'select',
editoptions: {
dataUrl: urlBase + '/AvailableConeTypes',
buildSelect: my.buildSelect
},
searchoptions: {
dataUrl: urlBase + '/AvailableConeTypes',
buildSelect: my.buildSelect
}
}
where
my.buildSelect = function(data) {
var response = jQuery.parseJSON(data.responseText),
s = '<select>', i, l, ri;
if (response && response.length) {
for (i=0, l=response.length; i<l; i += 1) {
ri = response[i];
s += '<option value="' + ri + '">' + ri + '</option>';
}
}
return s + '</select>';
};
This line of code shows a True,False dropdownlist for a column that has true, false values:
{
name: 'SReqdFlag', index: 'SReqdFlag', editable: true, edittype: 'select', editoptions: { value: '"":Select;true:True;false:False' }
}
Hope that helps!

Resources