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!";
}
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'm trying to validate a form that will send an email. At the moment the button returns formCheck() onclick. Which is meant to display a popup respective of field completetion.
I'm new to JS so I'm having a little trouble working out what I'm doing wrong as the outcome is always the else "Thanks".
<script>
function formCheck() {
if (document.getElementById("Name") === "")
{
alert("please enter name");
}
else if (document.getElementById("Email") === "")
{
alert("Please enter an email address");
}
else if (document.getElementById("Name") && document.getElementById("Email") === "")
{
alert("Please enter a Name and Email address");
}
else {
alert("Thanks");
}
}
</script>
To me it looks like I'm either not using an if statementcorrectly or its not picking up the fields are empty when defined as "". If anybody can point me in the right direction it would be much appreciated.
You should be comparing the value instead of the object itself:
document.getElementById("Name").value
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!)
please help me out on this little problem. I want to get the name of the image (with NO path and file extension) from an input field before that the form is submitted!
in other words, I want to check if this two name are the same, then proceed, if not, then return false;
My JavaScript code:
var pic = document.getElementById("photo1").value;
if (gyuru == null || gyuru == "" || gyuru == " ")
{
alert("Gyűrűszám nélkül nem lehet adatot lementeni!");
x.focus();
x.style.borderColor="#C30";
return false;
}else if (gyuru != pic){
alert("A kép neve nem egyezik meg a gyűrűszámal!");
return false;
}
And the image input form data:
<input type="file" id="photo1" name="photo1"/>
To get the filename without extension:
pic = pic.split('/').pop().split('\\').pop().replace(/[.][^.]+$/, "");
function validate() {
var x=document.getElementById("user").value;
var y=document.getElementById("pass").value;
if(x==null || x==" ") {
alert("Enter username");
}
if(y==null || y==" ") {
alert("Enter password");
}
}
As Twonky commented, we need some additional information. The code that you posted is just a function. I suppose you have two inputs and a button? Do you want the alerts to show when a user clicks the button and the input fields are empty? If you do, you need to add this function as a callback to onclick event.
More about the events:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
https://www.bitdegree.org/learn/onclick-javascript
https://www.w3docs.com/snippets/html/how-to-make-button-onclick-in-html.html
Edit: added corrected code and some links for further reading. The mistake was with looking for white space, instead for an empty string (" ", instead of "")
<!doctype html>
<html>
<head>
<title>Welcome</title>
<script>
function validateForm() {
var x=document.getElementById("user").value;
var y=document.getElementById("pass").value;
if(x==="" || x===null) {
alert("Enter username");
};
if(y==="" || y===null) {
alert("Enter password");
};
};
</script>
</head>
<body>
<div>
Username:<input type="text" name="un" id="user"/>
Password:<input type="password" name="ps" id="pass"/>
<input type="submit" onclick="validateForm()"/>
</div>
</body>
</html>
Further articles about these topics:
Stackoveflow thread about whitespace and empty strings
An article about the difference between == and ===
P.S.: I had also changed the element from form to div. Since you are using your function in this case as a security so the user wouldn't submit empty data, this is better for now, since form is submitted with your function call and div isn't. You can check the network tab to see, that the page reloads after the function is executed with form element and is not reloaded with the div element.
if(x === undefined || x === null || x.trim() === '') alert('Please enter a username');
if(y === undefined || y === null || y.trim() === '') alert('Please enter a password');