Custom message show in simple-react-validator library - javascript

I want to show my custom error message
this.validator = new SimpleReactValidator({
messages: {
email: "Invalid mail Id",
// OR
// will override all messages
},
});
My input tag is
<input type="text" className="form-control" id="email" placeholder="Email" required="" name="email" value={email} onChange={this.handelChange}
/>
{this.validator.message('email', email, 'required|email')}
I want to show my error message "Invalid email Id",
Please any one help me, Thanks

After submit, you need to use this.validator.showMessages() to show the error messages. Also make sure to re-render the form/component somehow so that the errors are displayed.
I have created a working example in the codesandbox for you.
Also, See the docs

You can add a custom message for your input by doing the following
const validator = new SimpleReactValidator({
validators: {
med_docs: {
required: true,
message: 'Please upload a valid medical document.',
rule: (val, params, validatorP) => !!(val && val.length > 0),
},
},
Here you can customise the rule and add whatever validation you want
The above rule that I have added is to check if the medical doc array has some value

Related

How to show error when user enter more than `one` or 1 character?

I am using ant design for my application.
https://ant.design/components/table/
I am facing one validation issue. I implemented table in my demo .when I click edit button it shows me input field
I am able to add validation of required .so empty is not allowed .but I want user only enter one or 1 character inside the input field else it shows an error.
Here is my code
https://codesandbox.io/s/thirsty-tesla-1nwph
return (
<td {...restProps}>
{editing ? (
<Form.Item style={{ margin: 0 }}>
{getFieldDecorator(dataIndex, {
rules: [
{
required: true,
message: `Please Input ${title}!`
}
],
initialValue: record[dataIndex]
})(getInput())}
</Form.Item>
) : (
children
)}
</td>
);
};
form error
https://ant.design/components/form/
I am able to add validation of required .so empty is not allowed .but I want user only enter one or 1 character inside the input field else it shows an error.
If you are saying "only the literal 1 or one should be valid inside the input", you can use
rules: [
{
required: true,
message: `Please Input ${title}!`
},
{
pattern: /^(1|one)$/,
message: "Only 1 or one are valid"
}
],
Othwerwise if it is length you can use max property. A list of all validation rules can be seen here: https://ant.design/components/form/?locale=en-US#Validation-Rules

how to get field value on change for FormItem in antd

I am having a hard time with antd's form.
I have this select field in this form and I want to get the value from it onChange but somehow not getting it to work properly.
say this is the item for which I want the values
<FormItem
{...formItemLayout}
label={fieldLabels.qcategoryid}
validateStatus={categoryError ? "error" : ""}
help={categoryError || ""}
>
{getFieldDecorator("qcategoryid", {
rules: [{ required: true, message: "Please select Category!" }],
onChange: this.handleCategoryChange
})(<Select>{categoryOptions}</Select>)}
</FormItem>
this is the categoryOptions
if (this.props.categories) {
categoryOptions = this.props.categories.map(item => (
<Select.Option
key={item.categoryid}
value={item.categoryid}
name={item.categoryname}
>
{item.categoryname}
</Select.Option>
));
}
I want both the name of the category and the id
so I created a handleCategoryChange which gets called onChange
and I am able to get the fields I want.
But, it seems that now, I have to click twice on the field to properly select it.
If I click it just once then it does show up in the console. but the field on the form still remains empty. when I click it again, then the field shows up in the form too.
So, what am I doing wrong here.
Ah,yes! Here's the handleCategoryChange function
handleCategoryChange = (value, e) => {
console.log("value is : ", value);
console.log("e : ", e);
this.props.form.setFieldsValue({ qcategoryid: value });
this.setState({
categorySelected: value,
categoryname: e.props.name
});
};
Just to make myself clear.
I need those values before I click submit.
not on submit.
maybe this will help Ant Design form API as of 22nd of May 2022
This was added in v4.20
const Demo = () => {
const [form] = Form.useForm();
const userName = Form.useWatch('username', form);
const { data: options } = useSWR(`/api/user/${userName}`, fetcher);
return (
<Form form={form}>
<Form.Item name="username">
<AutoComplete options={options} />
</Form.Item>
</Form>
);
};
I realize this is super late, but I think this might be what OP was looking for:
https://github.com/react-component/form/blob/3b9959b57ab30b41d8890ff30c79a7e7c383cad3/examples/server-validate.js#L74-L79
To set fields on a form dynamically, e.g. in a child via a callback, you could use
this.props.form.setFields({
user: {
value: values.user,
errors: [new Error('forbid ha')],
},
});
in a parent defined handleSelect method you called from the child on a selected value. you can alternatively use setFieldsValue if you dont want to pass an error field
Try this:
<FormItem
{...formItemLayout}
label={fieldLabels.qcategoryid}
validateStatus={categoryError ? "error" : ""}
help={categoryError || ""}
>
{getFieldDecorator("qcategoryid", {
rules: [{ required: true, message: "Please select Category!" }]
})(<Select onChange={this.handleCategoryChange}>{categoryOptions}</Select>)}
</FormItem>
And on the handleCategoryChange function
handleCategoryChange = (value, e) => {
this.setState({
categorySelected: value,
categoryname: e.props.name
});
};
Basically, changing the onChange from the getFieldDecorator helper to the Select, so it doesn't mess with antd's natural behavior, but gets the value and change on state
I've based this answer on the code to the registration form on their website. Specifically, the handleWebsiteChange function
https://ant.design/components/form/#components-form-demo-register
I have made a helper function to solve this problem, you have to pass the field
name you want to take out from the form and the form object.
const getFieldValue = (fieldName,form) => {
return Form.useWatch(fieldName,form);
}
console.log(getFieldValue("username"))
in above example I had to console updated username value.
demo
A quick response, and hopefully a quick solution. Rather than using onChange you may want to use onSelect/onDeselect handlers, per the documentation (https://ant.design/components/select/):
<Select onSelect={handleCategoryChange} .../>
I have found also that SELECT and other input components, due to their custom html nature operate differently, and so in my forms, I have often created them as dummy fields that are using to alter text/hidden inputs in order to achieve the desired behaviours in complex forms.
Either I am doing something wrong, or the ANT way is mildly annoying.
Hope this helps.

How do I submit a real-time validated form with Semantic UI and Meteor?

I have run into a huge problem with my form, which I validate in real time using Semantic UI.
The HTML:
<form class="ui form pin-form">
<div class="field">
<label>Email</label>
<input placeholder="name#example.com" name="email_input" type="text">
</div>
<div class="ui buttons">
<input type="submit" class="ui submit positive disabled button login-button" value="Log in">
</div>
</form>
I added the <form> tag myself and made the submit into an input so that I could access the regular submit form.
The real time validation comes from Semantic UI and a Meteor package: https://github.com/avrora/live-form-validator
On template render I do this:
if (!this._rendered) {
this._rendered = true;
pinForm = $('.ui.form.pin-form');
pinForm.form({
my_text_input: {
identifier: 'email_input',
rules: [
{
type: 'empty',
prompt: 'Type your email address'
},
{
type: 'email',
prompt: 'This is not yet a valid email address'
}
]
}
},
{
inline: true,
on: 'blur',
transition: 'slide down',
onSuccess: function () {
var submitButton = $('.ui.submit.button')
submitButton.removeClass('disabled')
return false
},
onFailure: function() {
var submitButton = $('.ui.submit.button')
submitButton.addClass('disabled')
}
})
}
The big problem here is that with return false it doesn't submit the form at all even when click the submit button, and without it it submits the form in real time, which I don't want!
Can anyone see a workaround or do I need to switch validation somehow?
If you want to do a Meteor.call, you could try doing it in the onSuccess function. The package does ask you to save the data manually within the onSuccess function.
The following code logged the email twice.
onSuccess: function () {
console.log("Email: ", $("input[name=email_input]").val());
// Submit your form here using a Meteor.call maybe?
return false;
},
You could alternatively look at aldeed:autoform for handling forms in Meteor.
This could be the stupidest question on all of SO. (Don't worry, I asked the question so I'm only dissing myself!)
Semantic UI literally provides the on: change setting, which will validate the form in real time instead of on: blur which it is set to now.
Oh, man...

The first element will error message to go on focus. Javascript

I have a form with some input fields:
Folder Name:
<input type="text" id="folderName" name="folderName" data-bind = "value: FolderName" />
Prefix:
<input id="prefix" name="prefix" data-bind = "value: Prefix" />
I validate those fields using jquery validation plugin:
rules: {
folderName: {
required: true
},
prefix: {
required: true,
exactLength: 4
},
}
When submitting the form with empty fields, error messages are displayed for both inputs. What I want to accomplish is the first element with error message to go on focus. My skills in javascript are rather poor so any working example will be greatly appreciated. Thank You!
drop something like this after your validation fires
// set focus to first input
$('body').find(':input:first').focus();

How to exempt element to be validated?

I'm using the validation plugin for jquery:
http://docs.jquery.com/Plugins/Validation.
I want to know how would I exempt a field to be validated? Currently all fields inside the form are automatically checked.
I am not sure if this will help since the element that I want to exempt is not included (obviously :) )
$("#contactForm").validate({
rules: {
first_name:{required: true,charsonly:true,minlength: 1 },
last_name:{required:true,charsonly:true,minlength: 1 },
birthday:{required:true,min:1,max:31 },
birthmonth:"required",
birthyear:"required",
username: {required: true,minlength:1,maxlength:32,username:true,notChinese:true,noSpecial:true},
password1:{required:true,minlength: 5,maxlength: 10, alphaNum: true },
password2:{required:true,minlength: 5,maxlength: 10, alphaNum: true, equalTo: "#password1"},
currency:"required",
address:{required: true,noSpecial:true,minlength:2},
city:{required: true,noSpecial:true,minlength:2},
state:{noSpecial:true},
countrycode:"required",
zip:{required:true,zipTest:true},
email:{required:true,email: true},
confirmemail:{required: true,equalTo: "#email",email:true},
phone:{required: true,minlength:6,maxlength:20,phoneUS:true},
cellphone:{required: true,minlength:6,maxlength:20,phoneUS:true},
custom06:{acceptIM:true}
} });
Found it.
I used the ignore validation method.
Here's the code
$("#myform").validate({
ignore: ".ignore"
})
It depends on class attribute. See examples:
This field is required and email format: it cannot be empty
input class="required email"
This field is NOT required and email format: it can be empty
input class="email"
This field is NOT required and doesnt have format: it can be empty
input class=""
Are you using some sort of server side technology? The validation library needs to have rules set, and if you are doing this in strictly javaScript (jQuery) it is manual.
UPDATE: You can remove rules with the following: http://docs.jquery.com/Plugins/Validation/rules#.22remove.22rules
Place the following at the end of the body.
$("selector").rules("remove");
You could set your own messages:
$("#contactForm").validate({
rules: {
input1: required,
input2: required,
no-validation: required,
input4: required,
},
messages: {
no-validation: ''
}
});
Just put an empty string for the field you donĀ“t want to show any message for..

Categories

Resources