How to use HTML form.checkValidity()? - javascript

Reading a website's source code that uses MVC, I struggled trying to understand some of it.
Code snippet of the view:
function submitForm (action) {
var forms = document.getElementById('form')
forms.action = action
if (forms.checkValidity()) {
forms.submit()
} else {
alert('There is still an empty field')
}
}
I want to execute some code if the form is missing certain inputs.

checkValidity() is a HTML5 method and
When the checkValidity() method is invoked, if the element is a candidate for constraint validation and does not satisfy its constraints, the user agent must fire a simple event named invalid that is cancelable (but in this case has no default action) at the element and return false. Otherwise, it must only return true without doing anything else.
Please learn more about how to use form validation constraints here.
There are number of useful methods you can use, customize and even build custom validation methods.
You also can find basic explanation and examples in w3schools.
Hope this helps.

For Me this works in jQuery
$('#formSection')[0].checkValidity();

just use a required
Example
<input type"text" id="id" required>
if you press the submit button there an alert text saying PLEASE FILL OUT THIS FIELD

Related

JQuery validate custom error message is not showing up

Following is the form validation javascript in my application:
$('#EmploymentHistoryForm').validate({
ignore: ':hidden, [readonly=readonly]',
rules: {
'MemberJob.Phone': {
PhoneFieldValidation: true
}
},
messages: {
'MemberJob.Phone': {
PhoneFieldValidation: $.viewUrl.url.invaliedPhoneMessage
}
},
showErrors: function (errorMap, errorList) {
ShowErrors(errorMap, errorList, this.validElements());
},
submitHandler: function (form, event) {
event.preventDefault();
return false;
}
});
Here, $.viewUrl.url.invaliedPhoneMessage is set at the cshtml page (in ASP.NET MVC), and while debugging the javascript I can see proper value in that variable when $('...').validate function gets hit.
I have registered a new validator "PhoneFieldValidation" in JQuery validators collection:
$.validator.addMethod("PhoneFieldValidation", ValidatePhoneAndAltPhone);
Following is the rendered HTML for the input control for which I have added this validation rule:
<input class="PhoneFieldValidation" id="MemberJob_Phone" name="MemberJob.Phone" type="text" required="required" aria-required="true">
I can see the validation getting fired correctly. That means, "ValidatePhoneAndAltPhone" method is getting called, and returning a boolean result based on the input.
However, the error message is not getting displayed properly. It displays "Warning: No message defined for MemberJob.Phone" instead of "Invalid Phone Number".
While debugging through customMessage function of jquery.validate.js, I could see "this.settings.messages" collection is not having the message for "MemberJob.Phone" field, and that looks to be the root cause of this issue.
Any idea of how to resolve this issue?
I know we can add "data-msg-[rulename]" attribute in the HTML tag which will fix the issue. But I am sure the current approach I am following is also correct. Seems I am missing something.
Any help on this will be much appreciated.
Thanks
You never mentioned where $.viewUrl.url.invaliedPhoneMessage comes from.
If there is already a message defined in your custom PhoneFieldValidation method, then you would not define a message within the messages object.
Otherwise, you cannot use a JavaScript variable within the messages object without a function.
The whole problem is being caused by the Unobtrusive plugin which is automatically constructing the .validate() method call. You cannot call .validate() more than once on the same form; and all subsequent calls are ignored. Instead, you can simply define the custom message for PhoneFieldValidation within its .addMethod() method.
$.validator.addMethod("PhoneFieldValidation", function(value, element) {
// your custom method function here;
}, "This is your custom validation error message");

Multiple errors per field in Mongoose validation

Has anyone workaround for getting all errors per field in Mongoose validation? Right now, when some field has an error, validation for that field stops, because of that, you need to resubmit form to see next error.
This behaviour might be fixed in future (https://github.com/Automattic/mongoose/issues/2612), but before that, I would love to see a workaround, which would let me to use validation method, for e.g.:
User.schema.path('hashed_password').validate(function (value) {
if ( ! something)
this.invalidate('password', 'Something is wrong with the password');
});
Note: Using validation method, I can bind error to any field, not just the one validated at the moment. Right now there is no plugin which would let me do that (I have tested mongoose-validator-all and mongoose-validate-all and those plugins are using different strategy).

How can I determine if all business rules are met in an entity form in Dynamics CRM 2013?

I have a form with two fields
e-mail
telephone
and a business rule that validates that at least one of them is set. There is a Silverlight application in the CRM that needs to know if the form can be saved or not. This should be done without saving it, thus invoking save() and catching exceptions is not an option. I can invoke Javascript from the Silverlight application, so a JS solution would be fine, too.
How can the SL application (or a JS function) know whether or not the form can be saved?
Happy coding
Arne
You say your business rule "validates" that one or the other is filled in. What action does it take if this is the case? I can think of several approaches to this, such as testing if one is NULL, make the other required.
You could just test to see if both are null, and show an error message against one or both. Displaying an error message from a rule will block saving of the record. Whether this will be enough to block your SL app from trying to save it as well, I'm not sure.
I solved the problem. In case this helps someone, I created business rules that make fields mandatory when some conditions are met. Then I created a JS function that checks if all fields that are mandatory are actually filled. This function did not work correctly for me. Here is the working version:
function IsAllMandatoryFieldsPopulated() {
var populated = true;
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
if (attribute.getRequiredLevel() == 'required') {
if(attribute.getValue() === null) {
populated = false;
}
}
});
if (populated)
return '';
return 'Put your validation message here';
}
It did not work because of some hassles you get when you call this function form SL, but that is out of scope for this question. Hope this helps someone.

asp.net disable/enable validator using Javascript

I have a complex form requiring me to switch specific validators on or off depending on selections made by the user.
ValidatorEnable seems to do the job, but it seems that when I call this method it actually fires the validation process as well, without the user actually hitting the submit button.
Is that how it works?
I eventually found the best way to do this was to use the following code:
var validatorObject = document.getElementById('<%=ValidHasShippingLocationZip.ClientID%>');
validatorObject.enabled = false;
validatorObject.isvalid = true;
ValidatorUpdateDisplay(validatorObject);
I wrote some code seems can meet your requests.
Iterate validators and enable these you needs.
ValidatorEnable(validatorObj, true);
then clear the screen,erase the error info.
The full code snippet can be found here http://codelife.cybtamin.com/enable-and-disable-asp-net-validator-by-javascript/

Validating e-mail from specific domains with RSV jquery plug-in

I'm trying to use Ben Keen's RSV Jquery plug-in to validate an e-mail address submitted through a registration form: users are only allowed to submit an e-mail address that belongs to a specific domain. I thought that using the plugin's reg_exp rule could be a solution, but I can't get it to work.
I'm a jquery newbie, so I'm probably making some very silly mistake: can someone point me to the right direction?
Here's the code I'm trying to use, adapted from one of Keen's demo:
<script type="text/javascript">
// a custom onComplete handler to prevent form submits for the demo
function myOnComplete()
{
alert("The form validates! (normally, it would submit the form here).");
return false;
}
var rules = [];
// standard form fields
rules.push("reg_exp,reg_exp_field1,/#mydomain\.tld$/gi,Please enter your valid e-mail (e.g. \"#mydomain\.tld\")");
$(document).ready(function() {
$("#demo_form3").RSV({
onCompleteHandler: myOnComplete,
rules: rules
});
});
</script>
Using the code above, when I submit a valid e-mail address, that is an address ending with #mydomain.tld I always get an alert. What am I doing wrong?
I have written RSV for many lines of code. It's very powerful.
However, you used it incorrectly.
you should define a customized function instead of its default email-format validation method.
you should put that "customized function" mentioned above into the validation array, but not put it in "myOnComplete" method, this method only called when all the validations are passed.
in RSV, a customized function only should return "true"(when passed) or "an Array"(when failed). but in the example above, you implemented as "return false".
Whatever, you have solved your problem in another way. :-) that's good.
Never mind, after further researche I found a simpler solution: following the advice in this forum thread I used jqueryValidate instead of rsv plug-in and added custom validate method.
I'm posting here my solution, maybe it could be useful for some other jquery newbie like me!
$(document).ready(function(){
$.validator.addMethod("gmail", function(value, element) {
return this.optional(element) || /^[\w-\.]+#(gmail\.com|yahoo\.com)+$/i.test(value);
}, "Email address must contain gmail or yahoo addresses.");
$("#register_member_form").validate();
});

Categories