How to escape an entity within jQuery function using jAlert? - javascript

Here's sample code:
$("#register-button").click(function(){
if (uname=="" || pname=="" || cemail=="" || remail=="") {
jAlert('Please fix the validation error','Title™');
return false;
}
});
Basically, if username, password, or email fields aren't filled correctly, a jAlert pops up that says "Please fix the validation error" containing a title that's trademarked. Unfortunately, this trademark is not properly an entity and does not render correctly.
I tried the following but it does not work correctly:
$("#register-button").click(function(){
if (uname=="" || pname=="" || cemail=="" || remail=="") {
jAlert('Please fix the validation error','Title™');
return false;
}
});
As you can see, the only difference is that I've included ™. However, it does not turn into ™ when the jAlert pops up.
How do I escape the jQuery in order for this entity to properly render?

Just define this on function level in your code:
String.prototype.htmlEscape = function () {
return this.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">");
}
And now you can use it as:
jAlert("Please fix the validation error".htmlEscape(),"Title™".htmlEscape());

Related

Why is my validation method for zip codes not working correctly

I have a form that uses asp:requiredvalidator and some custom javascript to apply a red 1px border around any field that hasn't been correctly filled in.
This works perfectly, but now I want to be able to immediately remove the red border when the user correctly fills in the field.
To achieve this, I am using Jquery's focusout() method to compare the user input to a regular expression. So far I have this correctly working on every field (including email validation) except zip code. For some reason, all the validation methods I have written work perfectly except for zip code.
Here is a working email validation for example
if (id == "email1" || id == "email2") {
emailValue = e.target.value;
if (validateEmail(emailValue)) {
$("#" + id).removeClass("ErrorControl");
}
else {
}
}
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);
}
This works perfectly and removes the red border as soon as the field losses focus and the email is valid.
But I cannot get my zip validator working, even though it works almost the exact same way.
Here is the non working zip example
//Zip code also require special validation to confirm
if (id == "zip") {
zipValue = e.target.value;
if (validateZip(zipValue)) {
$("#" + id).removeClass("ErrorControl")
}
}
//Simple zip validator
function validateZip(zip) {
var re = /^[0-9]{5}$/;
return re.test(zip);
}
Unfortunately this still removes the red border, even when I enter just letters in it! Why is this happening?
https://jsfiddle.net/hhjvstp3/
I have given both email and zip a class of ErrorControl since I cannot run asp validators on jsfiddle. This works exactly like I am describing. Email validates well, zip code removes the border no matter what.
Updated fiddle
You can see which line removes the ErrorControl class from zip
if (id == "firstname" || id == "lastname" || id == "address1" || id == "city" || id == "amount") {
//id == "zip" shouldn't be here
if (e.target.value != "") {
$("#" + id).removeClass("ErrorControl");
}
}

Uncaught TypeError: Cannot set property 'display' of undefined

I am in the process of migrating an existing platform to a new server. I am taking the opportunity to upgrade PHP ect and standardise/debug the code as the previous maintainers have had different standards.
I have opted for PHP version 5.4.33 for now, once I have managed to move everything over to mysqli I will look to go to a more recent version. I didnt think anything server side would make a difference to AJAX/JS? As far as I am aware is it not client side?
Since I have moved the code over I am having issues with AJAX/JS. I am not the greatest at AJAX/JS and could use some assistance please. Even though every submit works differently through the entire platform I do not want to remove the AJAX/JS that already exists. I will most likely use it as an opportunity to how to use it as it makes end user experience smoother.
Using Chrome to debug I am receiving the following error on clicking the Save button:
Uncaught TypeError: Cannot set property 'display' of undefined
email_user
onclick
This is the Save button code
<span id="loading" style="color: red; font-size: x-small; display: none; text-decoration: blink;">Loading... Please wait..</span><input type="button" value="Save" class="save" onclick="if(validate()){ email_user(); }" />
This is the function code for validate()
function validate() {
var errorString = "";
if(isBlank(document.getElementById("forename").value)) {
errorString += " - Please input a forename\n";
}
if(isBlank(document.getElementById("surname").value)) {
errorString += " - Please input a surname\n";
}
if(isBlank(document.getElementById("company_name").value)) {
errorString += " - Please select a company\n";
}
if(document.getElementById("username").value != "" || document.getElementById("password").value != "") {
if(isBlank(document.getElementById("username").value)) {
errorString += " - Please input a username\n";
}
if(isBlank(document.getElementById("password").value)) {
errorString += " - Please select a password\n";
}
}
//if not a solicitor then cases mandatory
if(document.getElementById("company_role_type_id").value == 2) {
if(document.getElementById("other_view_if").value == "") {
errorString += " - Please select who can view your cases\n";
}
}
if(document.getElementById("company_role_type_id").value == 3) {
if(document.getElementById("other_view_ea").value == "") {
errorString += " - Please select who can view your cases\n";
}
}
if(errorString) {
alert('Please correct the following items:-\n\n'+ errorString);
return false;
}
else {
return true;
}
}
This is the function code for email_user()
function email_user(){
if(skip_email == true){ $('user').submit(); }
var url = 'email_user.php';
var params = '?' + $('user').serialize() + '&from_edit=1';
$('loading').style.display = 'inline';
var myAjax = new Ajax.Request(
url,
{
method: 'get',
parameters: params,
onComplete: show_response
});
function show_response(this_request){
//alert(this_request.responseText);
var reply = this_request.responseText.evalJSON(true);
if(reply['status'] == false){ var blah = ''; }
else{ alert(reply['message']); }
//$('loading').style.display = 'none';
$('user').submit();
}
}
Thinking about it, maybe it is more to do with the Apache version?? Just in case Apache version is 2.2.15.
Any assistance you guys can give me will be greatly appreciated! If you need any more information please let me know.
Kind Regards,
n00bstacker
As previously stated in comments, your code has some issues, your line (the one that is triggering the error, can be optimized in the following way:
$('#loading').css("display","inline"); //Selector is ok now...
In the other hand, I also noticed that you have a second selector $('user') that won´t work. Remember that anything without a dot, or a sharp will be considered as an element selector (loading, and user elements, won´t exist in your document unless you created it.
Remember:
$("#myId") //id selector
$(".myClass") //class selector
If "user" is the form name, the code may work. Remember that you want to catch the form submit event.
Regards,
Guillermo
Try changing $('loading') to $('#loading')?

Javascript: Field validation

so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.

Javascript validation display string within webpage rather than alert

Hi I currently have a form on submission the following validation rule is checked:
<script language="JavaScript">
var frmvalidator = new Validator("contactform");
frmvalidator.addValidation("message","req","Please enter a valid message.");
</script>
function Validator(frmname)
{
this.formobj=document.forms[frmname];
if(!this.formobj)
{
alert("Error: couldnot get Form object "+frmname);
return;
}
if(this.formobj.onsubmit)
{
this.formobj.old_onsubmit = this.formobj.onsubmit;
this.formobj.onsubmit=null;
}
else
{
this.formobj.old_onsubmit = null;
}
this.formobj._sfm_form_name=frmname;
this.formobj.onsubmit=form_submit_handler;
this.addValidation = add_validation;
this.setAddnlValidationFunction=set_addnl_vfunction;
this.clearAllValidations = clear_all_validations;
this.disable_validations = false;//new
document.error_disp_handler = new sfm_ErrorDisplayHandler();
this.EnableOnPageErrorDisplay=validator_enable_OPED;
this.EnableOnPageErrorDisplaySingleBox=validator_enable_OPED_SB;
this.show_errors_together=true;
this.EnableMsgsTogether=sfm_enable_show_msgs_together;
document.set_focus_onerror=true;
this.EnableFocusOnError=sfm_validator_enable_focus;
}
However I would like the error message to be displayed on the webpage rather than an alert, could someone please achieve this.
The tutorial you are using cites the form validator as http://www.javascript-coder.com/html-form/javascript-form-validation.phtml If you read that, specifically at the top of the second page you will see:
Showing all the form validation errors together in a message box
If you want to show all the error messages together, then just call
the EnableMsgsTogether() function as shown below.
frmvalidator.EnableMsgsTogether();
The text which follows this provides further options for handling of error messages.
You could perhaps try that.

Check jquery unobtrusive validation is true by jQuery

I use MVC 3 Model Validation Attributes and jquery unobtrusive to show validation error message also use the script when form submitted return a confirm. So I need to check if the all fields are valid then return Confirm: some thing like the following pseudo-script:
$('div.FormNeedConfirm form').submit(function () {
if ($(this).validate() == true) {
var Message = $('#FormConfirmMessage').val();
return confirm(Message);
}
});
But I don't know what exactly should be in the if condition. What is your suggestion?
if ($(this).valid()) {
var Message = $('#FormConfirmMessage').val();
return confirm(Message);
}
if ($(this).validate() = true) // your if condition should be "==".
change to like this
if ($(this).validate() == true)

Categories

Resources