I am using this library https://github.com/asimism/native-validations in a form validation, it's working fine but I have an error message in the checkboxes group validation when I try to submit the group of checkboxes empty it appears: "null"
this is the demo link: you have to click "submit" without clicking any field in order to see the "null" message https://www.cssscript.com/demo/custom-html5-form-validator-native-validations/
https://codesandbox.io/s/8xr6vx5nnj?fontsize=14
apparentely, there is an error in this function
function checkBoxGroupValidate(event) {
//get all checked checkboxes for a group and if its null then mark it invalid or valid
var totalChecked = event.target.parentNode.querySelector("input[name$='[]']:checked");
if (totalChecked === null) {
var errorMessage = '';
if(event.target.dataset.requireError){
errorMessage = event.target.dataset.requireError;
}else if(event.target.parentNode.dataset.requireError){
errorMessage = event.target.parentNode.dataset.requireError;
}else {
errorMessage = OptionGroupMessage;
}
event.target.parentNode.classList.remove(SuccessClass);
event.target.parentNode.classList.add(ErrorClass);
if (event.target.parentNode.querySelector(HelpBlockSelector) === null) {
event.target.parentNode.insertAdjacentHTML("afterbegin", MessageTag.replace("{0}", errorMessage));
}
} else {
event.target.parentNode.classList.remove(ErrorClass);
event.target.parentNode.classList.add(SuccessClass);
var spanError = event.target.parentNode.querySelector(HelpBlockSelector);
if (spanError !== null) {
event.target.parentNode.removeChild(spanError)
}
}
}
The querySelector is returning null because is searching the error message on the childs elements in this case checkbox but they don't have data-require-error attribute the first time to get the error.
var errorMessage = groupParent.querySelector("input[name$='[]']").getAttribute('data-require-error');
instead use the parent directly
var errorMessage = groupParent.getAttribute("data-require-error");
Related
Hi im just starting to learn web development but I can't seem to find why my innerHTML won't appear on my page can someone help me ? I need to show these error messages if the fields are left empty but I can't seem to get it working for some reason :/
JS:
// B. email
const frmOrder = document.querySelector('#frmOrder');
const inpEmail = frmOrder.querySelector('#inpEmail');
const msgEmail = frmOrder.querySelector('.message');
// B. Dropdown
const selMeasure = frmOrder.querySelector('#selMeasure');
const msgMeasure = frmOrder.querySelector('.selMeasure .message');
//B. Checking
frmOrder.setAttribute('novalidate', 'novalidate');
frmOrder.addEventListener('sumbit', function (e) {
e.preventDefault();
let numErrors = 0 ;
msgEmail.innerHTML = '' ;
msgMeasure.innerHTML = '' ;
if (inpEmail.value == '' ) {
msgEmail.innerHTML = "please fill in ur email!";
numErrors++;
}
if (selMeasure.value == '' ) {
msgMeasure.innerHTML = "please fill in ur Measurement!";
numErrors++
}
if (numErrors == 0) {
frmOrder.sumbit();
lblMessage.innerHTML = `Het formulier is correct ingevuld`;
}
});
There are syntax errors in your code.
Change the word sumbit to submit.
The following code loops when the page loads and I can't figure out why it is doing so. Is the issue with the onfocus?
alert("JS is working");
function validateFirstName() {
alert("validateFirstName was called");
var x = document.forms["info"]["fname"].value;
if (x == "") {
alert("First name must be filled out");
//return false;
}
}
function validateLastName()
{
alert("validateLastName was called");
var y = document.forms["info"]["lname"].value;
if (y == "") {
alert("Last name must be filled out");
//return false;
}
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.onfocus = validateFirstName();
alert("in between");
ln.onfocus = validateLastName();
There were several issues with the approach you were taking to accomplish this, but the "looping" behavior you were experiencing is because you are using a combination of alert and onFocus. When you are focused on an input field and an alert is triggered, when you dismiss the alert, the browser will (by default) re-focus the element that previously had focus. So in your case, you would focus, get an alert, it would re-focus automatically, so it would re-trigger the alert, etc. Over and over.
A better way to do this is using the input event. That way, the user will not get prompted with an error message before they even have a chance to fill out the field. They will only be prompted if they clear out a value in a field, or if you call the validateRequiredField function sometime later in the code (on the form submission, for example).
I also changed around your validation function so you don't have to create a validation function for every single input on your form that does the exact same thing except spit out a slightly different message. You should also abstract the functionality that defines what to do on each error outside of the validation function - this is for testability and reusability purposes.
Let me know if you have any questions.
function validateRequiredField(fieldLabel, value) {
var errors = "";
if (value === "") {
//alert(fieldLabel + " must be filled out");
errors += fieldLabel + " must be filled out\n";
}
return errors;
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("First Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
ln.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("Last Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
<form name="myForm">
<label>First Name: <input id="fn" /></label><br/><br/>
<label>Last Name: <input id="ln"/></label>
</form>
Not tested but you can try this
fn.addEventListener('focus', validateFirstName);
ln.addEventListener('focus', validateLastName);
I am trying validate a data to set in an input. I want to use HTML validation.
For example, I want to check if "aaaa" is a valid data for an number input. I wanted use willValidate or validity but I can not set an invalid value, the console shows (Chrome):
The specified value "aaaa" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?
I have tried catch the error but it is not an Exception. I retrieve the input value and it is empty after the error.
var value = "aaaa";
try {
document.getElementById("input").value = value; // Shows a warn
} catch(err) {
console.log(err.message); // Nothing catching
}
console.log( document.getElementById("input").value ); // It is empty
See JSFiddle Demo
I want to check if a value to set is valid in the input type. I thought set the invalid value in the input and check willValidate or validity but the browser shows a warn and the input value is empty. The problem is that my frontend set the inputs values via JavaScript but the user pass the values. When an error occurs I need show the error to the user and not put only and input empty.
I know that the warn is not an Exception. I want know shows the error when set an invalid input value in any type.
var value = "aaaa";
document.getElementById("input").value = value;
if (document.getElementById("input").value == null || document.getElementById("input").value == "") {
alert("Invalid value");
}
function chkValidity(elemementID) {
var inpObj = document.getElementById(elemementID);
if (inpObj.checkValidity() == false) {
inpObj.setCustomValidity("This is not a number or a valid number. And this is my custom validity message for the value "+inpObj.value+" which is being inserted via javascript. Determinig \"required\",\"min\",\"max\" and checkValidity it is enough to do the work.");
document.getElementById("error").innerHTML = inpObj.validationMessage;
alert(inpObj.validationMessage);
} else {
document.getElementById("error").innerHTML = "This is valid number and within range";
}
}
var value = "aaaa";
document.getElementById("input").value = value;
chkValidity("input");
document.querySelector("#clickme").addEventListener("click", function(){
chkValidity("input");
});
<input type="number" id="input" required min="0" max="9999" step="1" />
<button id="clickme"> Click Me
</button>
<div id="error">
</div>
To check value being set by JavaScript, you can throw an Error, having .message set to warning displayed in the console, to catch if the input value does not match the same Regular Expression displayed in the console.
To check user input you can use onkeydown and onpaste events; use the <label> element to display message in your HTML, onfocus event to set the label's .innerHTML to empty string if the input value is empty an string.
Note, the message displayed in the console is also set at the input element's computedName property; though is not updated at user input and set to empty string following an alert() at the time of the catch.
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
var input = document.getElementById("input");
var label = document.querySelector("[for=input]");
function handleInvalid(el, val, e) {
console.log("value:", val, "computedName:", el.comptedName);
var message = "The specified value <mark>" + val
+ "</mark> is not a valid number. "
+ "The value must match to "
+ "the following regular expression: "
+ "<code style=background:#eee;padding:2px>"
+ "-?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?</code>";
// if `e` : `event` is not defined,
// that is `val` : `"aaaa"` set at `try`;
// not user input
if (!e) {
el.value = val;
};
if (!/-?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?/.test(val)) {
if (!e) {
// `throw` `Error` to `catch`
throw new Error(message);
} else {
label.innerHTML = message;
}
} else {
// if `val` is matches `RegExp`,
// set `label` `.innerHTML` to empty string
label.innerHTML = ""
}
}
function handleInput(e) {
label.innerHTML = "";
var text = e.clipboardData // handle `paste` event
? e.clipboardData.getData("text/plain")
// use `event.key` of `keydown` event
// if defined, else use `e.keyCode`
: e.key || String.fromCodePoint(e.keyCode);
handleInvalid(this, text, e);
}
function reset() {
// set `label` `.innerHTML` to empty string
if (input.value.trim() === "") {
label.innerHTML = "";
}
}
input.onkeydown = input.onpaste = handleInput;
input.onfocus = reset;
try {
var val = "aaaa";
handleInvalid(input, val)
} catch (e) {
label.innerHTML = e.message;
alert(input.computedName);
}
}
</script>
<style>
</style>
</head>
<body>
<form>
<input type="number" id="input" />
<label id="error" for="input"></label>
</form>
</body>
</html>
Here is a Plnkr example: https://plnkr.co/edit/mLgCQfBmvZHb5cNGZWtN?p=preview
It's because that's not an error but only a warning. You can check that in the console.
What you can do is check for isNaN(value)and throw an Error object.
try {
if(isNaN(value))
throw new Error("not a number");
else
document.getElementById("input").value = value;
} catch(err) {
document.getElementById("error").innerText = err.message;
}
jsFiddle as example
I have a javascript validation function.I need to check if required fileds are empty or wrong mail address.Required fileds empty is working But when i type mail like abc#abc or something wrong then it doent catch the error in my code.
When i type all required fileds but wrong email address ( abc#abc or abc.com like doesn't capture.)
My Code
function newsValidation() {
var status = true;
if (($.trim($('#txtNewsname').val()) == '') || ($.trim($('#txtnewsarea').val()) == '') ||
($.trim($('#txtemail').val()) == '')) {
$("#reqfield").removeClass("hidden");
if (!ValidateEmail($("#txtemail").val())) {
$("#emailval").removeClass("hidden");
}
status = false;
}
Email Validate Function
function ValidateEmail(email) {
var expr = /^([\w-\.]+)##((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
}
Your test for a valid email is inside the if block which test if the value is not null, so when you enter any value in the text box (whether its valid or not) the if (!ValidateEmail($("#txtemail").val())) { will never be called. Change your script to
function newsValidation() {
var status = true;
if (($.trim($('#txtNewsname').val()) == '') || ($.trim($('#txtnewsarea').val()) == '') || ($.trim($('#txtemail').val()) == '')) {
$("#reqfield").removeClass("hidden");
status = false;
} else if (!ValidateEmail($("#txtemail").val())) {
$("#emailval").removeClass("hidden");
status = false;
}
}
Side note: All this functionality is provide out of the box in MVC by simply adding the [Required] and [EmailAddress] attribute to your property and including the relevant scripts (jquery.validate.js and jquery.validate.unobtrusive.js) and #Html.ValidationMessageFor() helpers which means you get both client and server side validation (and it's all done correctly!)
Im trying to submit a form by javascript, after a specific field is validated.
im using
function doValidate(){
var error = false;
var nr = document.getElementById('number').value;
if (nr > '10'){
document.getElementById('number').className += " red";
error = true;
}
if (error = false) {
document.forms["new_qs"].submit();
}
}
but when error is false, just nothing happens!
I inspected the site with firebug, error is false, the document.forms seems to do nothing.
But in Online Tutorials this is working very good.
Here is a complete fiddle from the site http://jsfiddle.net/S7G9J/25/
What could be the problem/solution?
if (error = false) {
In the above, you are using assignment operator. =. Use == to compare
Also you are comparing string instead of numbers.
Try this:
function doValidate(){
var error = false;
var nr = Number(document.getElementById('number').value);
if (nr > 10){
document.getElementById('number').className += " red";
error = true;
}
if (error === false) {
document.querySelector('[type="button"]').submit();
}
}
The error lies in the line where you submit() the form.
In your fiddle, your form's id is "test". In your javascript, the form you're referencing should have an id of "new_qs". However, there is no such form, so there is no submit() processed.
document.forms[0].submit() will submit the first form in order of appearance in your HTML. So, try this:
function doValidate(){
var error = false;
var nr = document.getElementById('number').value;
if (nr > '10'){
document.getElementById('number').className += " red";
error = true;
}
if (error == false) { // need double equal here
document.forms[0].submit();
}
}