AJAX not showing validation error message

For the past two days, I've been grappling with an issue and can't seem to pinpoint where it's coming from.

After leaving the textbox, the Ajax call functions correctly and returns results as either true or false, triggering the success function. However, the image and error text are not appearing next to the textbox. Despite receiving a "Must be under 50 characters" message when entering more than 50 characters in the textbox, no message displays when typing in an existing username.

What could I be overlooking? Any suggestions?

I am using a DevExpress Text Box

Html.DevExpress().Label(
        edtSettings =>
        {
            edtSettings.ControlStyle.CssClass = "label";
            edtSettings.Text = "User Name:";
            edtSettings.AssociatedControlName = "UserName";
        }
    )
    .Render();
    Html.DevExpress().TextBox(
        edtSettings =>
        {
            edtSettings.Name = "UserName";
            edtSettings.ControlStyle.CssClass = "editor";
            edtSettings.ShowModelErrors = true;
            edtSettings.Width = 100;
            edtSettings.Properties.ValidationSettings.Assign(IserValidationHelper.UserNameValidationSettings);
            edtSettings.Properties.ClientSideEvents.Validation = "OnNameValidation";
            edtSettings.ControlStyle.BackColor = System.Drawing.Color.LightYellow;
        }
        )
        .Bind(DataBinder.Eval(IserUser, "UserName"))
        .Render();

This is the JavaScript code I have:

<script type="text/javascript">

function OnNameValidation(s, e) {

    if (e.value == null)
        e.isValid = false;

    $.ajax({
        type: 'POST',
        url: '/Admin/CheckUsername',
        dataType: 'json',
        data: { userName: e.value },
        error: function () { alert("error"); },
        success: function (Data) {
            if (Data.result == true) {
                e.isValid = false;
                e.errorText = "User Exits";
            };
        }
    });

    var name = e.value;
    if (name == "")
        e.isValid = false;

    if (name.length > 50) {
        e.isValid = false;
        e.errorText = "Must be under 50 characters";
    }

}

This is the method within my controller:

[HttpPost]
    public ActionResult CheckUsername(string userName)
    {
        bool status = WebSecurity.UserExists(userName);
        return Json(new { result = status });
    }

Answer №1

After resolving the issue with my $.ajax call, I made sure to include the setting for async (async:false,) since the default value is true. This adjustment has resolved the problem and now everything is functioning correctly.

function OnNameValidation(s, e) {

    if (e.value == null)
        e.isValid = false;

    $.ajax({
        type: 'POST',
        url: '/ISERAdmin/CheckUsername',
        dataType: 'json',
        async:false,
        data: { userName: e.value },
        error: function () { alert("error"); },
        success: function (Data) {
            if (Data.result == true) {
                e.isValid = false;
                e.errorText = "User Exists";
            };
        }
    });

    var name = e.value;
    if (name == "")
        e.isValid = false;

    if (name.length > 56) {
        e.isValid = false;
        e.errorText = "Must be under 56 characters";
    }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Launching a single modal for multiple posts

I have a collection of posts and for each post, I want the ability to open a modal. However, I am looking for a solution where I can use a single dynamic modal instead of creating multiple modals for each post. Here is the code I currently have: https://j ...

Store live text field group in their respective index

I am working on a project that involves creating dynamic description textareas based on the value selected from a dropdown list. The dropdown list contains numbers 1 through 5, and for each number chosen, I need to generate corresponding textareas with ser ...

What is the best way to transfer a JavaScript object with string values containing quotes from node.js to the browser?

I have a node/express application and need to send a JavaScript object to the browser. Currently, I achieve this by using JSON.stringify on the object and then embedding it into the HTML: In my Node.js/Express code: var myObject = /* fetched from databas ...

Issue with rendering in sandbox environment versus localhost

Here's a dilemma I'm facing - I have some HTML code on my localhost that looks like this: <div> <p>Go to: <a href="www.foobar.com">here</a></p> </div> On localhost, the output is "Go to: here" with 'he ...

Building objects with attributes using constructor functions

My question pertains to JavaScript constructor function prototypes. Suppose I have code like the following: a = function (name){this.name = name}; a['b'] = function (age){this.age = age}; c = new a('John'); c.a['b'](30); Is ...

Stop the Router from Displaying the Page momentarily prior to Redirecting

Currently, I have set up a session context for my NextJS application where users accessing pages within the /app/ directory are required to undergo an authorization check before being granted access. Although the logic is functioning correctly in redirect ...

Adjust the height of a div vertically in Angular 2+

Recently, I started using angular2 and I've been attempting to create a vertically resizable div without success. I have experimented with a directive for this purpose. Below is the code for my directive: import { Directive, HostListener, ElementRef ...

Discovering the real-time availability of form fields can be easily accomplished by utilizing jQuery AJAX within PHP

Currently, I am in the process of creating a validation system using jQuery within PHP. I have successfully implemented username and email availability checks. However, I am facing an issue where upon submitting the form, the data is not being inserted int ...

HTML View of JSON Object Hierarchy

Hello, I have been trying various methods but am struggling to figure out how to display the following JSON object as a tree HTML view with ul li items using JavaScript. Can anyone help me with this? [ { "CategoriesModelId": 7, "Name": "Parent ...

JQuery ajax fails to execute the success function

I've encountered an issue with my jQuery code. It successfully sends items to the controller for download, and I can see that the downloads are working fine as the response in the Chrome Network Tab looks okay. However, the success function never runs ...

What is the solution for the red underline issue with the @json Blade directive in VSC?

Everything seems to be functioning correctly with these variables, but I'm curious as to why they are underlined in red. Does anyone have a solution for this issue? Error message ...

Only line breaks are permitted in Mustache.js, all other HTML characters are escaped

After a user submits input, I am generating comments and displaying them using Mustache.js. When it comes to rendering the comments, I have found that replacing user-entered line breaks (\n) with <br/> allows them to display as HTML breaks. To ...

What is the best way to transmit real-time stdout data from a Node.js server to an AngularJS client?

I am currently facing an issue with a script that runs for a long time and generates output. The script is executed from nodejs using child_process, but I want to be able to send the output as soon as it starts executing without waiting for the script to c ...

Ways to incorporate JSON web token into every query string of my requests

Just recently, I grasped the concept of using JSON web tokens. Successfully, I can generate a JSON web token upon sign-in and have also established the middleware to authenticate my token and secure the routes that fall under the JSON verification middlewa ...

Ways to avoid overflow of dynamically added div element?

Currently, I am facing an issue while dynamically appending div elements with the .magnet class to my page. These elements end up overflowing the container boundaries and I am struggling to find a solution for this problem. If anyone could check out my j ...

What benefits come from employing jQuery for data storage techniques?

After learning more about jQuery data storage, I have a question. Is there any advantage to using either of these methods: $('#editCity').data('href', "xx"); var a = $('#editCity').data('href'); or $('#edit ...

Develop an Angular resolver that can be utilized across various scenarios

Im searching for a method to apply a single angular route resolve to all of my routes, each with different parameters: currently, my setup looks like this: { path: 'user/:any', component: UserprofileComponent, resolve ...

Tips for accessing nested JSON values using Selenium

Here is a JSON snippet to work with: "ACCOUNT": { "AmountDue": "$36,812.99", "OutstandingBalance": "$27,142.27", "StatementTotal": "$9,670.72", "StatementDate": "12/6/2018", "DueByDate": "12/23/2018", ...

Is it true that all events in JavaScript go through capturing and bubbling phases?

My current project involves binding one eventListener to an <audio> element for the play event and another eventListener to its parent element for the same event. I've observed that the callback for the child element always gets executed, while ...

Is it possible to target an iframe and display text simultaneously?

Trying to create a unique menu that interacts with an iframe and displays text in a separate div upon clicking. Example: • Menu item 1 clicked. • "https://wikipedia.org" loads in the iframe. • Address of the wikipedia page displayed in a diffe ...