Yup, basically, I am building a web form that need to provide different required form and validation function fallow by selected country.
I am using
<script type="text/javascript" src=" jquery-1.3.2.min.js" charset="utf-8"></script>
<script type="text/javascript" src=" jquery.validate.js" charset="utf-8"></script>
and here is my JS code
<script type="text/javascript" charset="utf-8">
function updatRequreForm (STATE,ZIPCODE) {
$("#frm_verification").validate({
rules: {
'form[country]' : "required",
'form[state]' : {required: STATE},
'form[zip]': {required: ZIPCODE},
},
messages: {
'form[country]' : "This field is required.",
'form[state]' : "This field is required.",
'form[zip]': "This field is required.",
});
};
function setRequreForm () {
var _cs = $('#country_select')[0];
if ('US' != _cs.value)
{
$('#state_star')[0].innerHTML = '';
$('#zip_star')[0].innerHTML = '';
updatRequreForm (false,false);
}
else
{
$('#state_star')[0].innerHTML = '*';
$('#zip_star')[0].innerHTML = '*';
updatRequreForm (true,true);
}
};
$(document).ready(function() {
setRequreForm ();
$('#country_select').change(function(){
setRequreForm ();
});
});
</script>
Here is my HTML:
<form id="frm_verification" action="some.php" method="POST">
<label for="country_select"><sup>*</sup>Country:</label>
<select name="form[country]" id="country_select">
<option value="">- Select -</option>
<option value="US" selected="selected">United States</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
<label for="select-state"><sup id="state_star">*</sup>State/Province/Region:</label>
<span id="states_select">
<select id="select-state" name="form[state]">
<option value="">- Select -</option>
<option value="AK">Alaska</option>
</select>
</span>
<span id="states_text" style="display:none;">
<input type="text" name="form[state]" value="" id="state" />
</span>
<label for="zip_code"><sup id="zip_star">*</sup>ZIP/Postal Code:</label>
<input type="text" id="zip_code" name="form[zip]" value="" id="zip">
<input type="submit" value="Submit" id="submit_btn" class="submit">
</form>
Basically, what I need to create is:
1.When user select US on country selection, the State and Zip area become required.
2.When user select Zambia on country selection, the State and Zip area become non-required.
Problem:
When I first load the page and click the Submit button with empty field, the form successfully validate each fields and shows warning. However selecting of the Zambia, the validation is not working.
Guess:
I have removed “setRequreForm ();” on ready function like:
$(document).ready(function() {
//setRequreForm ();
$('#country_select').change(function(){
setRequreForm ();
});
});
And tried to select Zambia, and tried to validate the form and it works. So I think calling “validate()” twice causes error.
Well I stuck with this for a while. Please help me to figure this out, I will really appreciate that.
You can't call validate more than ones becouse you run validate plugin more than one and this lead to errors.
You can setup your validator like this:
$("#myform").validate({
ignore: ".ignore"
})
Ignore tells to validator: field which has ignore css class should not be validated.
When you change requirements then add to specified fields css class "ignore":
$("#field1").addClass("ignore");
otherwise remove this class:
$("#field2").removeClass("ignore");
Related
I got a project using asp.net core 3.1 MVC.
It contains a form with a selection that is disabled.
<div class="col-12 mb-3">
<select asp-for="SelectableItem" class="multi-select form-control" id="selectedItem" disabled="disabled" required="required">
<option value="">-- Select Item --</option>
</select>
<span asp-validation-for="SelectableItems" class="text-danger"></span>
</div>
The fully rendered html
<select class="multi-select form-control" id="selectedItem" disabled="" required="required"
data-val="true" data-val-required="Selected Item is required"
name="SelectedItem">
<option value="">-- Select Item --</option>
</select>
This selection is disabled until the user checks a box, which then populates the select element and enables it, as the content depens on wat checkbox has been selected.
When the user tries to submit the form the validation of JQuery.Validation.Unobtrusive validates everything except that disabled field, as the field is required however i would like for it to be validated as well.
I only want it to be enabled for that one form, so not all disabled elements throughout the application, but can't seem to get it to work.
I tried the following and some variants of it.
$('form').validator.setDefaults({ignore: null})
$('form').data('validator').settings.ignore = "";
$('form').validator.setDefaults({ignore: []})
$('#selectableItem').Validate().settings.not('[disabled]')
Non of these seem to do anything, the disabled select refuses to get validated, and all other suggestions like readonly doesn't work on select elements, nor do i want it to be globally allowed, as that would mess up some other forms.
If you really want to validate all disabled form fields, the relevant line in the plugin is:
.not( ":submit, :reset, :image, :disabled" )
Follow the steps:
1.Find the jquery.validate.js in your project.
2.Open the js and press ctrl + F to find the line contains disabled,them comment on this line(or you could remove the :disabled in this line):
3.If you use the default asp.net core project,remember to change the _ValidationScriptsPartial.cshtml.Because this view add a reference for jquery.validate.min.js,but you modify the jquery.validate.js(If you still want to use min.js,please read the docs and learn how to bundle and minify static assets ):
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script> //change here...
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
Here is a working demo:
Model(add [Required]attribute):
public class Test
{
[Required] //add this
public string SelectableItem { get; set; }
}
View(remove required="required"):
#model Test
<form method="post">
<input type="checkbox" />
<div class="col-12 mb-3">
<select asp-for="SelectableItem" class="multi-select form-control" id="selectedItem" disabled="disabled">
<option value="">-- Select Item --</option>
</select>
<span asp-validation-for="SelectableItem" class="text-danger"></span>
</div>
<input type="submit" value="Create" />
</form>
#section Scripts
{
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(document).ready(function () {
$('input:checkbox').change(function () {
if (this.checked) {
//add to select list
$("#selectedItem").append($("<option></option>")
.attr("value", "1")
.text("aa"));
$("#selectedItem").append($("<option></option>")
.attr("value", "2")
.text("bb"));
$("#selectedItem").append($("<option></option>")
.attr("value", "3")
.text("cc"));
// $("selectedItem").prop('required', true);
$("#selectedItem").removeAttr('disabled');
}
else {
//remove item from select list
$("#selectedItem").empty().append($("<option></option>")
.attr("value", "")
.text("-- Select Item --"));
$("#selectedItem").prop('disabled', true);
}
});
});
</script>
}
Result:
I want the to get the required in the html page if none is selected.
function validation() {
var country = getElementById("country");
if (country.value = "") {
documnet.getElementById("countryy").innerHTML = "Required";
return false;
} else
return true;
}
<form onsubmit="return validation();">
<select id="country"><span id="countryy"></span>
</select><br>
<input type="submit" name="Submit" value="Submit">
</form>
Why The Validation is not working for the provided html/ js code. I want the to get the required in the html page if none is selected. I am new to js learning.
Several issues
Spelling mistake in the document.getElementById
missing document on the other document.getElementById
No preventDefault which will submit the form if any JS errors
= is assignment - you need == or === to compare
span needs to be outside the select
You did not use value="Default" in the "NONE" options
It is not recommended to have inline event handlers. Here is a better version
Note I added a class to toggle the required in case the user changes the select to conform
window.addEventListener("load", function() {
const errorSpan = document.getElementById("countryy"); // cache the elements
const country = document.getElementById("country");
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = country.value; // get the value
if (val === "") {
e.preventDefault(); // stop submit
}
errorSpan.classList.toggle("hide",val); // hide if value
})
country.addEventListener("change",function() { // if user changes the select
errorSpan.classList.toggle("hide",this.val); // hide if value
})
})
.hide { display : none; }
<form id="myForm">
<select id="country">
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select> <span id="countryy" class="hide">Required</span><br>
<input type="submit" name="Submit" value="Submit">
</form>
HOWEVER you could remove all the script and just add required attribute to the select and keep the empty default
<form id="myForm">
<select id="country" required>
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select><span id="countryy"></span><br>
<input type="submit" name="Submit" value="Submit">
</form>
Use required attribute in the select tag. It will considered in html 5 validation.
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_select_required
I am doing error validation in Angular as follows.
<select ng-model = "color" class = "form-control"
ng-options = "color as color for color in colors" required>
<option value="">Choose an option</option>
</select>
<span ng-show="serviceForm.color.$error.required"> My custom error message </span>
The error validation shows up as expected, however, the custom message does not. Instead, I get the following.
This looks nice but how do I replace it with my custom message? It'd be cool if I know where that is coming from so I can edit it.
In addition, my custom message appears if I take out
<option value="">Choose an option</option>
and then it always appears. Why is this?
This message most probably comes from your browser as it does form validaten.
You have to add the novalidate attribute to your form to disable it:
<form novalidate>
Working Plnkr
You can replace HTML5 validation message of that specific field with space on form submit. It will prevent displaying the message and will not affect other HTML5 validation message.
JavaScript:
$scope.ValidateInput = function(){
var email = document.getElementById("colorId");
if (email.validity.valueMissing) {
email.setCustomValidity(" ");
} else {
email.setCustomValidity("");
}
}
HTML:
<form name='serviceForm'>
<select name='color' id='colorId' ng-model = "color" class = "form-control"
ng-options = "color as color for color in colors" required>
<option value="">Choose an option</option>
</select>
<span ng-show="serviceForm.color.$error.required"> My custom error message </span>
<input type='submit' ng-click='ValidateInput()' value='Submit'>
</form>
<select ng-model = "color" class = "form-control" name="lstColor"
ng-options = "color as color for color in colors" data-msg-required="Please select color from list" required>
<option value="">Choose an option</option>
</select>
Try above and hope will solve your problem
<form novalidate> can be used to avoid these messages.
But you can also use setCustomValidity function when oninvalid event occurs to replace it with your custom message.
Like:
<input class="form-control" type="email" required="" placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')"></input>
Helpful explanation here.
I have the following code that checks to see that two select fields are identical. The code works alright when called with onsubmit. However after doing this validation the form is still submitted. How can i prevent the script or my form from submitting the incorrect data.
Please see code below:
var fieldalias="Email address field"
function verify(element1, element2) {
var passed=false
if (element1.value=='') {
alert("Please fill out the "+fieldalias+"!")
element1.focus()
}
else if (element2.value=='') {
alert("Please verify the "+fieldalias+"!")
element2.focus()
}
else if (element1.value!=element2.value) {
alert("The two "+fieldalias+"s do not match")
element1.select()
}
else
passed=true
return passed
}
You didn't include your HTML, so I'm going to assume you've added onsubmit() to your form element.
If so, make sure your call looks like this:
onsubmit="return verify(element1, element2)"
(replace element1 and element2 accordingly)
If this assumption is not correct, please include some additional detail so we can better assist.
Try calling stopImmediatePropagation() on the event to prevent any further processing of the submit event by any other handlers in the form element or higher level elements.
Call that code with different event, like i.e: onchange, or onfocusout. This way the validation will be performed every time user enter some values to your fields, certainly before submitting.
EDIT:
I'm not sure if I understand you correctly but I would have attached your JS code this way:
First assign your select box to the variable:
var object_input = document.getElementById("selectId");
And then:
if(object_input.addEventListener)
{
object_input.addEventListener('blur', focus_lost);
object_input.addEventListener('keypress', checkForEnter);
}
else
{
object_input.attachEvent('onblur', focus_lost);
object_input.attachEvent('onkeypress', checkForEnter);
}
and then perform your validation ith focus_lost or checkForEnter.
Assuming that in the html code you have something like this:
<form action="test2.html" method="post" onsubmit="return verify(e1, e2);">
<input type="text" name="e1" /><br/>
<input type="text" name="e2" /><br/>
<input type="submit" value="Validate" />
</form>
You have to put in onsubmit event:
return verify(e1, e2);
so you will not go to the submiting page if the data is not valida
EDIT:
I think the problem is the
element1.select()
in the 3rd if, that this select method does not exist for a select object.
You can use a
element1.focus()
The code that will work is:
var fieldalias="Email address field"
function verify(element1, element2){
var passed=false;
if (element1.value==''){
alert("Please fill out the "+fieldalias+"!");
element1.focus();
}
else if (element2.value==''){
alert("Please verify the "+fieldalias+"!");
element2.focus();
}
else if (element1.value!=element2.value){
alert("The two "+fieldalias+"s do not match");
element1.focus();
}
else
passed=true;
return passed;
}
And
<form action="test2.html" method="post" onsubmit="return verify(document.getElementById('e1'), document.getElementById('e2'));">
<select id="e1">
<option value="One">One</option>
<option value="two">two</option>
<option value="Three">Three</option>
<option value="four">four</option>
</select><br/>
<select id="e2">
<option value="One">One</option>
<option value="two">two</option>
<option value="Three">Three</option>
<option value="four">four</option>
</select><br/>
<input type="submit" value="Validate" />
</form>
I'm trying to write a custom method to validate a date. The date however exists in three text boxes. Furthermore, there may be multiple instances of this date.
<div class="customDate">
<input class="month" id="dob_Month" maxlength="2" name="dob.Month" type="text" />
/
<input class="day" id="dob_Day" maxlength="2" name="dob.Day" type="text" />
/
<input class="year" id="dob_Year" maxlength="4" name="dob.Year" type="text" />
</div>
On submit, I'd like to validate any div containing the customDate class. I.e. make sure all boxes have been filled, make sure ranges are correct, etc. I'm using the following code:
$.validator.addMethod("customDate", function(element) { return false;}, "error message");
The validation function isn't firing however. What am I missing? Also, is there a better way to do this.
Note: I've stubbed out the functionality for the actual validation logic. I just need to know how to get the validation method to fire.
I have managed to create multiple field validation without use of a hidden field by following the guide at
http://docs.jquery.com/Plugins/Validation/multiplefields and amending it accordingly
might be overkill though :)
html code
<div class="whatever">
<!-- dob html -->
<div id="dobdate">
<select name="dobday" class="dateRequired" id="dobday">
<option value="">Day</option>
<option value="1">1</option>
</select>
<select name="dobmonth" class="dateRequired" id="dobmonth">
<option value="">Month</option>
<option value="January">January</option>
</select>
<select name="dobyear" class="dateRequired" id="dobyear">
<option value="">Year</option>
<option value="2010">2010</option>
</select>
<div class="errorContainer"> </div>
</div>
<br />
<div id="joinedate">
<!-- date joined html -->
<select name="joinedday" class="dateRequired" id="joinedday">
<option value="">Day</option>
<option value="1">1</option>
</select>
<select name="joinedmonth" class="dateRequired" id="joinedmonth">
<option value="">Month</option>
<option value="January">January</option>
</select>
<select name="joinedyear" class="dateRequired" id="joinedyear">
<option value="">Year</option>
<option value="2010">2010</option>
</select>
<div class="errorContainer"> </div>
</div>
<br />
<input name="submit" type="submit" value="Submit" class="submit" title="Submit"/>
</div>
jquery code
// 1. add a custom validation method
$.validator.addMethod("CheckDates", function(i,element)
{
// function with date logic to return whether this is actually a valid date - you'll need to create this to return a true/false result
return IsValidDate(element);
}, "Please enter a correct date");
// 2. add a class rule to assign the validation method to the relevent fields - this sets the fields with class name of "dateRequired" to be required and use the method youve set up above
$.validator.addClassRules({
dateRequired: { required:true, CheckDates:true}
});
// 3. add a validation group (consists of the fields you want to validate)
$("#myForm").validate(
{
submitHandler: function()
{
alert("submitted!");
},
groups:
{
dob: "dobyear dobmonth dobday", joined : "joinedyear joinedmonth joinedday"
},
messages: { dob : " ", joined : " " // sets the invidual errors to nothing so that only one message is displayed for each drop down group
},
errorPlacement: function(error, element)
{
element.parent().children(".errorContainer").append(error);
}
});
JavaScript code
function IsValidDate(_element)
{
// just a hack function to take an element, get the drop down fields within it with a particular class name ending with day /month/ year and perform a basic date time test
var $dateFields = $("#" + _element.id).parent();
day = $dateFields.children(".dateRequired:[name$='day']");
month = $dateFields.children(".dateRequired:[name$='month']");
year = $dateFields.children(".dateRequired:[name$='year']");
var $newDate = month.val() + " " + day.val() + " " + year.val();
var scratch = new Date($newDate );
if (scratch.toString() == "NaN" || scratch.toString() == "Invalid Date")
{
return false;
} else {
return true;
}
}
I would try triggering an event on form submit before the validation which appends the values from the individual day/month/year inputs together into a separate hidden input, and then validate the hidden input instead.
You add a hidden field
<input id="month" maxlength="2" name="month" type="text" />
<input id="day" maxlength="2" name="day" type="text" />
<input id="year" maxlength="4" name="year" type="text" />
<input id="birthday" name="birthday" type="text" />
then concatenate the values in the hidden, and validate that field.
$('#day,#month,#year').change(function() {
$('#birthday').val($('#day').val()+'/'+ $('#month').val()+'/'+ $('#year').val());
});
then validate the hidden value.
I'm pretty sure that the validation plugin only supports validating inputs, not arbitrary DOM elements. The elements function filters out anything that isn't an element as well as submit, reset, image buttons and disabled inputs.
What you'd want to do is have validators for month, day, and year. Month and day would need to reference each other's values in order to perform correct validation logic.