Hi I am new to HTML and JavaScript. I want to check the users phone number input for any letters, and print out those letters within the error message.
I'm a bit lost at the moment, can I save input as a string (as shown by the pseudo code saving input as InsertLetter). As well as put any string characters that are letters into an error message?
<form onsubmit="return isnumb()">
<label for="ph"> Enter Phone: </label>
<input type="text" id="phnumb"> <span
id="message"></span>
//InsertLetter = phnumb output
</form>
<script>
function isnumb() {
if (document.getElementById("phnumb").match =([a-z]))
{document.getElementById("message").innerHTML =
"<em> Number includes letter" + InsertLetter + "</em>";
return false;}
else return true;
It is far better to use <input type="tel"> in this situation. On that occasion user input should follow the given pattern which you can check with. Use Form Validation for the rest of the work, for example:
const phone = document.getElementById("phone");
const button = document.getElementsByTagName('button')[0];
const errorMessage = document.querySelector('p.error');
button.addEventListener('click', (e) => {
if (!phone.validity.valid) {
showError();
e.preventDefault();
}
});
phone.addEventListener('keyup', (e) => {
if (phone.validity.valid) {
errorMessage.innerHTML = '';
} else {
showError();
}
});
function showError() {
if (phone.validity.valueMissing) {
errorMessage.textContent = "Phone is required";
}
if (phone.validity.patternMismatch) {
errorMessage.textContent = "You are not supposed to use characters like this one: " + phone.value;
}
if (phone.validity.valid) {
phone.setCustomValidity("");
}
}
.error {
color: red;
}
<form>
<label for="phone">Phone Number (Format: +99 999 999 9999)</label>
<input type="tel" id="phone" name="phone" pattern="[\+]\d{2}[\s]\d{3}[\s]\d{3}[\s]\d{4}" required>
<p class="error"></p>
<button>Submit</button>
</form>
First of all i want to give u an answer of user should insert only number :`
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitForm() {
var phonenumber = document.forms["myForm"]["notanumber"].value;
if (isNaN(phonenumber)) {
alert("only number required");
} else {
alert("submit");
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" id="notanumber" />
<input type="submit" onclick="submitForm()" />
</form>
</body>
</html>
-> isNaN() is an inbuilt function in js, if variable is not a number, it return true, else return false.
the simple code :
restric the user from clicking any key, Only numbers allowed.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submit() {
alert("submited");
}
function noAlphabets(e) {
var phonenumber = document.forms["myForm"]["notanumber"].value;
var x = e.which || e.keycode;
if (x >= 48 && x <= 57) {
return submit();
} else {
alert("insert only numbers");
return false;
}
}
</script>
</head>
<body>
<form id="myForm">
<input
type="text"
id="notanumber"
onkeypress="return noAlphabets(event)"
/>
<button type="button" onclick="submit()">Submit</button>
</form>
</body>
</html>
Related
I am trying to validate the text input in my html. I only want alphabets and spaces. In the beginning, the validation worked but now it is not and I cannot seem to find the problem. It still submits the form with the invalid field. Please see the code below
index.html
<div class="full-form">
<form class=form-info action="cv.html" onsubmit="return handlesubmit()" >
<div class="f-header">
SIGN UP
</div>
<div class="bdetails">
<label for="fname">First Name</label><br>
<input type="text" name="fname" id="f_name" placeholder="First Name" onfocus="checkFName()" onblur="BlurFName()" required><br>
<p class="error_message" id="First_em">Name must contain only alphabets(A-Z)</p>
</div>
<script type="text/javascript" src="test.js"></script>
</form>
test.js
function checkData(){
if(BlurFName()){
}
return false;
}
function handlesubmit(){
checkData();
passvalue();
}
/*
Function to check if the name inputted is valid when the input is focused
*/
function checkFName(){
let name_len=/^[A-Za-z]+$/;
let fname= document.getElementById("f_name");
if(!fname.value.match(name_len)){
document.getElementById("First_em").style.display = "inline";
return true;
}
};
/*
Function to check if the name inputted is valid when the input is blurred
*/
function BlurFName(){
let name_len=/^[A-Za-z]+$/;
let fname= document.getElementById("f_name");
if(fname.value.match(name_len)){
document.getElementById("First_em").style.display = "none";
return false;
}
};
With function handlesubmit you need to return false or true.
I suggest use
e.preventDefault();
to easier handle Form submiting
You are not returning anything from your validation method. You need to do something like this:
function validateName () {
const inp = document.getElementById("fname");
const isValid = inp.value.trim().length > 0;
inp.classList.toggle('error', !isValid);
return isValid;
}
function validateGuess () {
const inp = document.getElementById("guess");
const isValid = +inp.value.trim() > 10;
inp.classList.toggle('error', !isValid);
return isValid;
}
function validate () {
const isNameValid = validateName();
const isGuessValid = validateGuess();
return isNameValid && isGuessValid;
}
.error { border-color: red; }
<form onsubmit="return validate()">
<label for="fname">name</label> <input type="text" name="fname" id="fname" /><br/>
<label for="guess">guess</label> <input type="number" name="guess" id="guess" />
<button>Submit</button>
</form>
How can I show the message if the user types a restricted symbol?
For example, if the user types * in the input field, the error message can show A filename cannot contain any of the following characters: \/:*?"<>|. I hope someone can guide me how to do it. Thanks.
<!DOCTYPE html>
<html>
<body>
<h1>How to show error message</h1>
<input type="text" class="form-control blank" id="function_code" name="function_code" title="function_code" onpaste="return false">
</body>
</html>
<script>
document.getElementById("function_code").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("></\":*?|".indexOf(chr) >= 0)
return false;
};
</script>
My expected result is like below the picture if the user types the restrict symbol in the input field:
Use the input event along with a regular expression, like so:
const input = document.getElementById("function_code");
const error = document.getElementById('error');
const regex = /[\\\/:*?"<>|]+/;
input.addEventListener('input', (e) => {
const value = e.target.value;
if (regex.test(value)) {
input.value = value.slice(0, value.length - 1);
error.textContent = 'A filename cannot contain any of the following characters: \/:*?"<>|';
} else {
error.textContent = '';
}
});
input {
padding: 8px 10px;
border-radius: 5px;
font-size: 1.2rem;
}
#error {
display: block;
color: red;
margin: 5px 0 0 0;
}
<input type="text" id="function_code" name="function_code">
<span id="error"></span>
Firstly I would wrap the input in a form.
After that you can use the setCustomValidity function for the input field to set a custom message if the condition is true. When you hit enter, or submit the form, you will see the error message.
This way you can give any custom message for your input.
Pay attention to the else block for handling no error cases.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity
<!DOCTYPE html>
<html>
<body>
<h1>How to show error message</h1>
<form>
<input type="text" class="form-control blank" id="function_code" name="function_code" title="function_code" onpaste="return false">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("function_code").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("></\":*?|".indexOf(chr) >= 0) {
this.setCustomValidity('A filename cannot contain any of the following characters: \/:*?"<>|');
} else {
this.setCustomValidity('');
}
};
</script>
</body>
</html>
Use HTML5 Pattern Match, below I have used the pattern ([a-zA-Z0-9]+) which simply means characters only latin alphabet and numbers 0-9. You can include the space character with
([a-zA-Z0-9]+\s{1}[a-zA-Z0-9]+)
You can learn more about regex here
This will not prevent author from entering wrong keypresses, it will only validate input. I will Include another approach to show custom error.
<form >
<input type="text" class="form-control blank" id="function_code" name="Option an" title="A name cannot contain irregular characters" pattern='([a-zA-Z0-9]+)' onpaste="return false">
<button >Submit</button>
</form>
Second approach. Use Javascript and write error to a div tag.
<!DOCTYPE html>
<html>
<body>
<h1>How to show error message</h1>
<input type="text" class="form-control blank" id="function_code" name="function_code" title="function_code" onpaste="return false">
<div id="error-box"></div>
</body>
</html>
<script>
function showError (key) {
var errBox = document.querySelector("#error-box");
errBox.textContent = "The character " + key.toString() + " is not allowed!";
//Dismiss the error
window.setTimeout(function () {
errBox.textContent = "";
}, 10000)
}
document.getElementById("function_code").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("></\":*?|".indexOf(chr) >= 0)
showError(chr)
return false;
};
</script>
I am trying to take a username and password as input and if the entered username and password are admin admin I want to forward them to a new php file. I dont understand where I am going wrong. Any help. Thank you in advance
<html>
<head>
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getelementbyId(log).value;
var pass=document.getelementbyId(password).value;
window.alert("stored");
if((user=="admin")&&(pass="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
</head>
<body>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</html>
Javascript is case sensitive, getelementbyId should be getElementById and id's needs to be wrapped in quotes.
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getElementById('log').value;
var pass=document.getElementById('password').value;
window.alert("stored");
if((user=="admin")&&(pass=="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
Also Note, You have submit button in your form .. which is not handled in validate function, either you can make <input type="button" ... or handle event in validate method.
getelementbyId should be getElementById & enclose the ID name by quote
var user=document.getElementById("log").value;
var pass=document.getElementById("password").value;
And compare by == instead of =
if((user=="admin")&&(pass=="admin"))
^^^
change onclick="validate()" to onclick="return validate();".
this way, when validate returns false, the form won't click. you'd also have to change the validate func to return false when the form doesn't validate, the resulting code would be:
<html>
<head>
<title>
User Validation : 2nd Program
</title>
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
</head>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</text>
</body>
try this one
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
Update: continue and break illustrated.
while(true) {
// :loopStart
var randomNumber = Math.random();
if (randomNumber < .5) {
continue; //skips the rest of the code and goes back to :loopStart
}
if (randomNumber >= .6) {
break; //exits the while loop (resumes execution at :loopEnd)
}
alert('value is between .5 and .6');
}
// :loopEnd
I have written the code so far and came up with this. I have to
Make sure the user input numbers into the text boxes and I was given errors using the Xhtml format, one, the '&&' sign gave me errors and due to online help, I was told I needed to use //
As I student learning Javascript I have no idea what this is or means, but as I placed it there, I was given more errors and my code crashed up after the javascript was added.
Thanks for the help in advance
<head>
<script type = 'text/javascript'>
// <![CDATA[
$('#submit').click(function(){
validateRange();
validateRa();
})
function validateRange() {
var txtVal = document.getElementById("CustomerID").value;
var txtVal1=parseInt(txtVal);
if (txtVal1 >= 3000 && txtVal1 <= 3999) {
return true;
}
else {
alert('Please enter a number between 3000-3999');
return false;
}
}
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
}
// ]]
</script>
<title>Account Lookup</title>
</head>
<body>
<h1> Please Provide Your Information</h1>
<p><input type="text" id="AcctNo" value="Account Number"/></p>
<p><input type="text" id="CustomerID" value="CustomerID" onchange="validateRange()"/></p>
<p><input type="text" name="Type" value="Account Type" onchange="validateRange()"/></p>
<p><input type="text" name="balance" value="Balance"/></p>
<p class="submit" />
<input type="submit" name="commit" value="Submit" id="submit" /><button type="reset" value="Clear">Clear</button></p>
</body>
</html>
EDITED
try using this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
validateRange();
validateRa();
});
});
function validateRange() {
var txtVal = document.getElementById("CustomerID").value;
var txtVal1=parseInt(txtVal);
if (txtVal1 >= 3000 && txtVal1 <= 3999) {
return true;
}
else {
alert('Please enter a number between 3000-3999');
return false;
}
}
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
}
</script>
<html>
<title>Account Lookup</title>
<body>
<h1> Please Provide Your Information</h1>
<p><input type="text" id="AcctNo" value="Account Number"/></p>
<p><input type="text" id="CustomerID" value="CustomerID" onchange="validateRange()"/></p>
<p><input type="text" name="Type" value="Account Type" onchange="validateRange()"/></p>
<p><input type="text" name="balance" value="Balance" /></p>
<p class="submit" />
<input type="submit" name="commit" value="Submit" id="submit" /><button type="reset" value="Clear">Clear</button></p>
</body>
</html>
BTW the function validateRa missing the closing curly braces you need to add } before // ]]
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
} //<= this is missing in your code
// ]]
I've this code:
<html>
<head>
<script type="text/javascript">
function validate(){
var name=document.frm.name.value;
if(name.indexOf("A")==0){
alert(name);
}
}
</script>
</head>
<body>
<form name="frm" action="test.php">
Enter name:<input type="text" name="name" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" onblur=""/>
<input type="submit"/>
</form>
</body>
</html>
In above code, I'd tried to validate textfields when they lose focus. The script working fine if the name starts with A. But I want if the user enter different name which doesn't start with A it will return the focus to the textfield name. For that I'd written this script:
<script type="text/javascript">
var name = document.frm.name.value;
if(name.indexOf("A") == 0){
alert(name);
}else{
document.frm.name.focus();
}
</script>
then it doesn't works.
Anybody could help with that what should I do to request focus of textfield name?
I've only a little knowledge of javascript.
Just give an id for you form and refer it with document.getElementById('form_id'). Use of name attribute in this context has been deprecated over a decade ago. Also name for input should be something else than "name", rather use username or sth.
HTML:
<form id="frm" action="test.php">
Enter name:<input type="text" name="username" id="username" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" id="email" onblur=""/>
</form>
JavaScript:
function validate(){
var form = document.getElementById('frm');
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
form.username.focus();
}
}
Instead of retrieving the id of the form, you can also pass the form to validate() as an argument: onblur="validate(this);". Then use that argument as a form in the eventhandler:
function validate(form){
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
form.username.focus();
}
}
EDIT
Focus doesn't seem to work without a delay, you can try this (the inputhas an id="username"):
function focusTo (elm) {
elm.focus();
return;
}
function validate(){
var form = document.getElementById('frm');
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
alert('error');
setTimeout(function () {focusTo(form.username);}, 10);
}
}
modifiy your script like this
<html>
<head>
<script type="text/javascript">
function validate(){
var name=document.frm.name.value;
if(name.indexOf("A")==0){
alert(name);
}
}
</script>
</head>
<body >
<form id="frm" action="test.php">
Enter name:<input type="text" name="username" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" onblur=""/>
<input type="submit" onclick="check()"/>
</form>
<SCRIPT LANGUAGE="JavaScript">
<!--
function validate()
{
var name = document.getElementById('frm').username.value;
if(name.indexOf("A") == 0){
alert(name);
document.getElementById('frm').email.focus();
}else{
document.getElementById('frm').username.focus();
}
}
function check()
{
var name = document.getElementById('frm').username.value;
if(name.indexOf("A") == 0){
}else{
alert("Please enter a name starting with 'A'");
document.getElementById('frm').username.focus();
}
}
//-->
</SCRIPT>
</body>
</html>
You want to execute function validate() on event onblur. in the script you have written the code for focusing, but not added it in a function.
try this document.frm.username.focus(); . i hope it will work.