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!)
Related
Im trying to first, check if both fields are not empty. if empty, alert user its empty. Then check if both user and password math and if they do match, then alert('welcome'). but if I type anything in the boxes, it passes and says welcome? Help!
const container = document.querySelector('.container');
const userInput = document.querySelector('#username');
const passInput = document.querySelector('#password');
const button = document.querySelector('button');
button.addEventListener('click', () => {
if (!userInput.value || !passInput.value) {
alert('One or more fields are empty. Please enter password and username');
}
if (!userInput.value == 'user21' || !passInput.value == 'user21') {
alert('password or username inavlid')
} else if (userInput.value == 'user21' && passInput.value == 'user21') {
alert(`Welcome ${userInput.value}`);
}
})*
Remove * at the end of your code and put ;
This:
if (!userInput.value == 'user21' || !passInput.value == 'user21') {
evaluates the ! first. It's like:
if ((!userInput.value) == 'user21' || (!passInput.value) == 'user21') {
which of course won't result in the comparison you want.
Check if the username and password match, and if they don't, just have a plain else, without an else if there.
button.addEventListener('click', () => {
if (!userInput.value || !passInput.value) {
alert('One or more fields are empty. Please enter password and username');
} else if (userInput.value == 'user21' && passInput.value == 'user21') {
alert(`Welcome ${userInput.value}`);
} else {
alert('password or username inavlid')
}
})
Also consider
using a proper modal instead of alert
if this is something you want any sort of reasonable security for, validate the logins using a backend database instead of hard-coding it on the front-end (which is trivially bypassable)
I have created functions to validate my form. But I want them all to run at once when I click the submit button. So, I have a formValidate function, and then I have a firstNameValidate, lastNameValidate ect.
My question is, how would I create the formValidate function to run the functions i have, but ONLY submit the form if all of them are true?
function firstNameValidate() {
// Making sure that the firstname input is not blank
if (firstName.value.length == 0) {
// If the firstname input is blank, then return the error text below
error.innerHTML = 'Please Enter a Valid First Name, Cannot be Blank';
// Error text css class
error.className = 'error';
// Making sure that the browser window focuses on the error
firstName.focus();
// Does not let the browser submit the form
// this statement makes sure that the input has only letters
return false;
} else if (!firstName.value.match(letter)) {
// // If the input has something other then numbers, show this error.
error.innerHTML =
'Please Enter a Valid First Name, Cannot contain characters(!##) or numbers';
// // error text css class
error.className = 'error';
// browser window focuses on error
firstName.focus();
// Form does not submit
return false;
}
if (firstName.value.length > 0 && firstName.value.match(letter)) {
error.className = '';
error.innerHTML = '';
return true;
}
}
I can get the first name and last name to validate, however if one them is filled out it sends the form. So the return true and return false I think are wrong.
function firstNameValidate() {
if (firstName.value.length == 0) {
error.innerHTML = 'Please Enter a Valid First Name, Cannot be Blank';
error.className = 'error';
firstName.focus();
return false;
}
if (!firstName.value.match(letter)) {
error.innerHTML = 'Please Enter a Valid First Name, Cannot contain characters(!##) or numbers';
error.className = 'error';
firstName.focus();
return false;
} else {
//intended code goes here , or simply return true.
}
}
If you want to do strict checking then write all the validation in if statement, and if everything is filled properly then do the correct code in an else statement,
and call the above function on form onsubmit or on a button click it will do the work..
Hope this helps ..!!
I have some JavaScript that is supposed to act as an example of how you can validate prompt box inputs.
User clicks button, enters a name, the JavaScript validates the input and displays an appropriate message. If the name is fine, it says it is a good name, if you enter a number/symbol it says invalid input (all good so far). However, when the user clicks "cancel" on the prompt box, the message displays "null" is a good name. I have tried to catch this but it doesn't seem to work. How can I make it display a message saying you did not enter a valid name when the user clicks "cancel"?
Here is the JS fiddle for it: http://jsfiddle.net/TurgidWizard/jzzsqu06/
html:
<button onclick="Validation()">Click Me</button>
<p id="vresult"></p>
Javascript:
function Validation() {
document.getElementById("vresult").innerHTML = "";
PetName = prompt("Please enter your favourite pet's name:", "");
var T = Test(PetName);
if (T == false | T == "null") {
document.getElementById("vresult").innerHTML = "You did not enter a valid name!";
} else {
document.getElementById("vresult").innerHTML = PetName + " is a lovely name, good choice!!";
}
}
function Test(str) {
return /^[a-zA-Z]+$/.test(str)
}
Notice how I tried to use "if (T == false | T == "null")" to capture "null" ready for the invalid message.
Your syntax is a bad here:
if (T == false | T == "null")
null shouldn't be a string, or is || not |.
You also want to be checking if PetName is null, not the result of the regex.
The line should look like this:
if (!T || !PetName)
Here's your fiddle: http://jsfiddle.net/jzzsqu06/1/
just check if str is null (as opposed to "null")
function Test(str) {
return (str !== null) && /^[a-zA-Z]+$/.test(str);
}
then simply check
if (T === false) {
prompt will return the entered value if OK or return is pressed, including empty strings "", and null if Cancel is pressed.
Incorporating this line in your if condition deals with the cancel option:
if (T != '' && T != null){
document.getElementById("vresult").innerHTML = "You did not enter a valid name!";
}
I am trying to remake a jQuery script by (http://jorenrapini.com/blog/javascript/the-simple-quick-and-small-jquery-html-form-validation-solution). This script is checking if a from is filled, if not a error message will appear.
What I want to do is to only get the error message when one of two form input-fields are filled out, if none of them are then they should be ignored. The form fields are named "firstinput" and "secondinput" (you can see their id in the code).
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Can anybody please help me with a solution, I would really appreciate it.
/A girl that spend a LOT of time solving this without luck :(
I would wrap your for loop in a conditional that evaluates if one or the other has a value.
if($("#field1").val() == "" && $("#field2").val() == ""){
//Ignore
}else{
//Do something
}
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
if($("#firstinput").val() != "" || $("#secondinput").val() != "")
{
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Two entered passwords should be the same, and I want to display a notification when they're not matching. The target is to display the notification during typing and not after pressing the save Button.
I am new to javascript and I have also tried the functionname function() notation.
following js:
function updateError (error) {
if (error == true) {
$(".error").hide(500);
}else{
$(".error").show(500);
}
};
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return true;
}
return false;
};
document.ready(function(){
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
});
and HTML:
#Html.Password("password")
#Html.Password("password-check")
<span class="error">Errortext</span> </td></tr>
but it doesn't works..
Thx!
Edit:
Now i've changed the JS code to:
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
--> now it works, but only once, after the user typed a matching password, validation stops working
Solved, problem was Quoting:
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
You are doing opposite
if (error == true) {
$(".error").show(500);
}else{
$(".error").hide(500);
}
Edit as per comment :
Try placing name within quotes like
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
In the checkSame, you may want to use indexOf to check if passwordVal contains checkVal since when typing, the password is not equal yet.
if (passwordVal.indexOf(checkVal)>-1 || checkVal.indexOf(passwordVal)>-1 ) {
return true;
}
As int2000 said, fire the checkSame on keyup seems weird, but if it's what you want, OK.
Try to change your checkSame function as follows:
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return false;
}
return true;
};
Remember that you're passing the result of checkSame to updateError, so if the passwords are the same you have no error.