JavaScript wrong if...else logic - javascript

I have a problem. There is something wrong with the code as even when the input like abc56, it still alert "Enter your name". Or when the input is abc, it should be displayed "Perfect" instead of "Enter your name". The input only allows characters not number and I think the regex is correct, the only wrong is the logic. Can you guys help me?
var check=document.forms["check"]["name"].value;
var reg=/^[a-zA-Z]+$/;
function ipt(){
if(check !== ""){
if(check.match(reg)===false){
alert("Only enter character please");
}
else{
alert("Perfect");
}
}
else{
alert("Enter your name");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
<script src="./check.js" defer></script>
</head>
<body>
<form name="check" onsubmit="ipt()">
<label for="name">Name</label>
<input type="text" id="name" name="name">
<button type="submit">Submit</button>
</form>
</body>
</html>

you get the value of document.forms["check"]["name"] on page load.
not the value onsubmit event
and your regex usage is wrong, use RegExp.prototype.test()
it return a boolean value ( true or false)
do
const name_elm = document.forms.check.name
, reg = /^[a-zA-Z]+$/
;
function ipt() {
if (!!name_elm.value) // or if (name_elm.value !== '')
{
if (reg.test(name_elm.value))
{ alert('Perfect') }
else
{ alert('Only enter character please') }
}
else {
alert('Enter your name');
} }

You can clean up the if statement by using an else if.
When you check for a value in a form, use value when you need to see what the current value is.
var check = document.forms["check"]["name"];
var reg = /^[a-zA-Z]+$/;
function ipt(){
// check if its empty
if (check.value === "") {
alert("Enter your name");
// check if it matches the pattern
} else if (!check.value.match(reg)) {
alert("Only enter character please");
} else {
// Success!
alert("Perfect");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
<script src="./check.js" defer></script>
</head>
<body>
<form name="check" onSubmit="return ipt()">
<label for="name">Name</label>
<input type="text" id="name" name="name">
<button type="submit">Submit</button>
</form>
</body>
</html>

Related

Javascript: why setCustomValidaty doesn't show up on first submission but it does on the second?

I'm trying to validate a login form but I cannot understand the reason why when I give a wrong input the message from setCustomValidation doesn't show up the first time I click on the submit button (actually input). However when I click on the same button a second time the error message appears as it should. Why is that?
Here's the code.
function validate(){
console.log("check validate()")
var email = document.getElementById("email");
var psw = document.getElementById("psw");
const patt = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email.value=="" && psw.value==""){
email.setCustomValidity("You need to insert email and password!");
return false;
}
else if ( email.value==""){
email.setCustomValidity("Insert your email address");
return false;
}
else if (psw.value==""){
psw.setCustomValidity("Insert password");
return false;
}
else if ( !patt.test(email.value) ){
email.setCustomValidity("This is not an email!");
console.log("Subcase works");
return false;
}
}
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Game</h1>
<div>
<form onsubmit="return validate()" method="POST" action="login.php">
<input id="email" type="text" placeholder="email">
<input id="psw" type="password" placeholder="password">
<input type="submit" id="login-btn" value="Accedi">
</form>
</div>
</body>
</html>
Firstly, according to the documentation for setCustomValidity:
You must call the reportValidity method on the same element or nothing will happen.
The reason it works the second time is because when the custom validity message is set, when the "submit" button is clicked again, the browser's built-in form validation takes over and blocks the submit. That is why you do not see the "check validate()" message in the console log on subsequent submits.
Therefore, merely adding something like email.reportValidity() after your email.setCustomValidity is not a solution because on subsequent submits, the submit event handler will not get called, because the form never gets submitted due to the non-null custom validity message. If you try this, you will see that you get the same error message even after filling out the email and password fields. To fix this, you can either add novalidate to the form to bypass the browser validation, or you can clear the custom validity message when the input changes using the input's onchange event.
Here is a working example by adding novalidate to the form and using reportValidity().
function validate(){
console.log("check validate()")
var email = document.getElementById("email");
var psw = document.getElementById("psw");
const patt = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email.value=="" && psw.value==""){
email.setCustomValidity("You need to insert email and password!");
email.reportValidity();
return false;
}
else if ( email.value==""){
email.setCustomValidity("Insert your email address");
email.reportValidity();
return false;
}
else if (psw.value==""){
psw.setCustomValidity("Insert password");
psw.reportValidity();
return false;
}
else if ( !patt.test(email.value) ){
email.setCustomValidity("This is not an email!");
email.reportValidity();
console.log("Subcase works");
return false;
}
}
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Game</h1>
<div>
<form onsubmit="return validate()" method="POST" action="login.php" novalidate>
<input id="email" type="text" placeholder="email">
<input id="psw" type="password" placeholder="password">
<input type="submit" id="login-btn" value="Accedi">
</form>
</div>
</body>
</html>
Here is a working example using the onchange event on the input fields and using reportValidity(). Notice in this case, the onsubmit handler is only called after the validity message has been cleared and not every time you click the submit button.
function validate(){
console.log("check validate()")
var email = document.getElementById("email");
var psw = document.getElementById("psw");
const patt = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email.value=="" && psw.value==""){
email.setCustomValidity("You need to insert email and password!");
email.reportValidity();
return false;
}
else if ( email.value==""){
email.setCustomValidity("Insert your email address");
email.reportValidity();
return false;
}
else if (psw.value==""){
psw.setCustomValidity("Insert password");
psw.reportValidity();
return false;
}
else if ( !patt.test(email.value) ){
email.setCustomValidity("This is not an email!");
email.reportValidity();
console.log("Subcase works");
return false;
}
}
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Game</h1>
<div>
<form onsubmit="return validate()" method="POST" action="login.php">
<input id="email" type="text" placeholder="email" onchange="event.target.setCustomValidity('')">
<input id="psw" type="password" placeholder="password" onchange="event.target.setCustomValidity('')">
<input type="submit" id="login-btn" value="Accedi">
</form>
</div>
</body>
</html>

Modify onclick attribute on field condition

I've created a form that goes something like this:
<form action="#" class="header_form clearfix">
<input type="text" placeholder="Enter Your Address" id="autocomplete">
Enter Your Address
</form>
I want to place a Javascript condition to check if the text input has text in it before the button would have the onclick parameters. If it has no text on keyup, the onclick is not on button. How to do so?
If you are using jQuery, you could do something like this:
$('.btn').on('click', function() {
var email = $.trim( $('#autocomplete').val() );
if(email.length) {
window.location = '/address?address='+email;
} else {
alert('Enter your email first');
}
});
$.trim is there to at least prevent empty spaces triggering a valid submit.
In any case you'd better go with an EMAIL regex pattern: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
This will disable the link if its not a valid email address too
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$( document ).ready(function() {
$('#autocomplete').bind('input', function() {
if ($(this).val().trim().length === 0) {
document.getElementById('myButton').removeAttribute('href');
} else {
if (validateEmail(document.getElementById("autocomplete").value) === true) {
document.getElementById('myButton').setAttribute("href",'/address?address=' + document.getElementById("autocomplete").value);
} else {
document.getElementById('myButton').removeAttribute('href');
}
}
});
document.getElementById('myButton').removeAttribute('href');
});
</script>
<form action="#" class="header_form clearfix">
<input type="text" placeholder="Enter Your Address" id="autocomplete" />
Enter Your Address
</form>
</body>
</html>

JavaScript form-validate without alert

What is wrong with my JavaScript? I want to show a errormessage next to the validate-field, but it doesnt show anything.
function validate() {
if (document.myform.firstname.value == "") {
document.getElementById('errorFirstname').innerHTML = "Error";
return false;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="jsformular.js"></script>
<meta charset="utf-8">
</head>
<body>
<div id="formBody">
<form name="myform" onsubmit="return validate()" method="post">
<div class="formField">
<div class="formFieldElement">
<label for="firstname">Firstname:*</label>
</div>
<div class="formFieldElement">
<input type="text" name="firstname">
</div>
<div class="formFieldElement formError" id="errorFirstname"></div>
</div>
</form>
</body>
</html>
you lost } in validate function
function validate() {
if (document.myform.firstname.value == "") {
document.getElementById('errorFirstname').innerHTML = "Error";
return false;
}
}
it's work
You were missing the close bracket at the end of your function.
function validate() {
if (document.myform.firstname.value == "") {
document.getElementById('errorFirstname').innerHTML = "Error";
return false;
}
}
When I typed nothing in the field and hit the enter key, it showed the error message.
For finding issues like this in future, I would highly recommend using the developer console included with Chrome or Firefox. It immediately flagged the error for me with the following error message:
Uncaught SyntaxError: Unexpected end of input

More Simple Password System Stuff

Sorry guys, first time playing around with this. Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<title>SuM BUTtonsS DOe</title>
<link rel="stylesheet" href="buttons.css"/>
</head>
<body>
<p>Please enter the password</p>
<form id="enter" onSubmit="javascript:passCheck()">
<input id="password" type="password" placeholder="Password">
</form>
<p id="incorrect"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
}
}
</script>
</body>
</html>
When I enter the wrong password, INCORRECT PASSWORD comes up, but only for a fraction of a second. Then it's gone again. No idea why.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<title>SuM BUTtonsS DOe</title>
<link rel="stylesheet" href="buttons.css"/>
</head>
<body>
<p>Please enter the password</p>
<form id="enter" onSubmit="javascript:passCheck()">
<input id="password" type="password" placeholder="Password">
</form>
<p id="incorrect"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
return false;
}
}
</script>
</body>
</html>
On submit, the form will trigger the default action, which in this case is to submit the contents to the same page (for lack of an action property).
So what you're seeing is the JavaScript runs and changes the style to show the error message, then the page reloads.
To ensure the page doesn't reload put return false at the end of passCheck. Better would be to use addEventListener and event.preventDefault(), but that's a little bit more involved.
<p>Please enter the password</p>
<form id="enter" onSubmit="passCheck(); return false;">
<input id="password" type="password" placeholder="Password">
<input type="submit" value="Submit"/>
</form>
<p id="incorrect" style="display: none"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
}
}
</script>

Decimal in javascript

The text box should accept onli decimal values in javascript. Not any other special characters. It should not accept "." more than once. For ex. it should not accept 6.....12
Can anybody help???
You can use regex:
function IsDecimal(str)
{
mystring = str;
if (mystring.match(/^\d+\.\d{2}$/ ) ) {
alert("match");
}
else
{
alert("not a match");
}
}
http://www.eggheadcafe.com/community/aspnet/3/81089/numaric-validation.aspx
You can use Regex.test method:
if (/\d+(\.\d{1,2})/.test(myTextboxValue)) //OK...
JQuery Mask plug in is the way to go!
http://www.meiocodigo.com/projects/meiomask/#mm_demos
If you mean you do not want anything but an integer or a decimal to be typed into the field, you'll need to look at the value
as each key is pressed. To catch pasted input, check it again onchange.
textbox.onkeyup=textbox.onchange=function(e){
e= window.event? event.srcElement: e.target;
var v= e.value;
while(v && parseFloat(v)!= v) v= v.slice(0, -1);
e.value= v;
}
probably you want to validate a form input before sending it to the server. Here is some example:
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validate(){
var field = document.getElementById("number");
if(field.value.match(/^\d+(\.\d*)?$/)){
return true;
} else {
alert("Not a number! : "+field.value);
return false;
}
}
</script>
</head>
<body>
<form action="#" method="post" onsubmit="return validate();">
<input type="text" id="number" width="15" /><br />
<input type="submit" value="send" />
</form>
</body>
</html>
I just whipped this up. Useful?
<html>
<head>
<script type="text/javascript">
function validNum(theField) {
val = theField.value;
var flt = parseFloat(val);
document.getElementById(theField.name+'Error').innerHTML=(val == "" || Number(val)==flt)?"":val + ' is not a valid (decimal) number';
}
window.onload=function(){
validNum(document.getElementById('num'));
}
</script>
</head>
<body>
<form>
<input type="text" name="num" id="num"
onkeyup="return validNum(this)" /> <span id="numError"></span>
</form>
</body>
</html>

Categories