Categories
discuss

How to trigger ASP.NET Core client-side validation from JavaScript

Is there any way to trigger ASP.NET Core client-side validation from JavaScript?

I have a Razor Pages page with a <form> that includes content like this:

<div class="row">
    <div class="col-md-6">
        <label asp-for="LocationModel.Location" class="control-label"></label>
        <input asp-for="LocationModel.Location" class="form-control" />
        <span asp-validation-for="LocationModel.Location" class="text-danger"></span>
    </div>
    <div class="col-md-6">
        <label asp-for="LocationModel.LoadsPerMonth" class="control-label"></label>
        <input asp-for="LocationModel.LoadsPerMonth" class="form-control" />
        <span asp-validation-for="LocationModel.LoadsPerMonth" class="text-danger"></span>
    </div>
</div>

If I submit the form, any validation errors are highlighted and displayed. Is there any way to trigger this from JavaScript?

I’m not actually submitting the form to the server. I just want to use the values in JavaScript. But I’d like to use ASP.NET Core validation, if I can. I can see that I can just set the text of the validation <span>s. Maybe I could do that if I knew how to make the control border red the way the validation does.

I found a number of examples that do this, but not for ASP.NET Core or Razor Pages.

Answer

You can do this with unobtrusive validation. To do that, you need to include the partial view that renders the jQuery unobtrusive validation scripts. To do that, add the following to the bottom of your view:

@section Scripts {
    // You can find the partial in ~/Views/Shared
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}

Next up, as a silly example to validate the form from JavaScript on load, you can add a script to that same Scripts section, underneath the inclusion of the partial:

@section Scripts {
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
    <script type="text/javascript">
        $(function () {
            $('#formID').validate();

            if ($('#formID').valid() === true) {
                console.log("valid");
            } else {
                console.log("invalid");
            }
        });
    </script>
}

Update per comments

@model SiteViewModel

<form asp-action="Index" id="formID" method="post">
    <input asp-for="Name" />
    <span asp-validation-for="Name"></span>
    <input type="submit" />
</form>

@section Scripts {
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
    <script type="text/javascript">
        $(function () {
            $('#formID').validate();

            if ($('#formID').valid() === false) {
                console.log("invalid");
            } else {
                console.log("valid!");
            }
        });
    </script>
}

where SiteViewModel is just:

public class SiteViewModel
{
    [Required]
    public string Name { get; set; }
}
Categories
discuss

flutter – android – http.get never returns in release mode

I am writing a flutter app for android and ios. To log in, the app uses the http package (version 0.12.2) : http.Response response = await http.get(url);. In iOS, everything works fine. In Android, the debug mode works also fine, however, if I build the apk and install the app from this release apk, the async method http.get never returns. I use Android 9 on a OnePlus 3 (OxygenOS 9.0.6).

I am very new to flutter and can’t figure this out. A similar issue is open in github but concerns flutter for web.

Here is a minimal code to reproduce. To test it, you should build the apk (Build > Flutter > Build apk)), copy and paste the apk in your phone files, install the app from the apk, press the button PRESS ME, done will never be displayed.

  • main.dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Test flutter'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _status = "Press the button";

  void _test() async {
    String url = "http://dummy.restapiexample.com/api/v1/employees";

    // Send HTTP request to the server
    http.Response response = await http.get(
        url
    );

    setState(() {
      _status = "done";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // Test button
            RaisedButton(
                onPressed: _test,
                child: Text(
                  "PRESS ME",
                ),
              ),
            Text(
              '$_status',
            ),
          ],
        ),
      ),
    );
  }
}
  • pubspec.yaml
name: flutter_test_app
description: Test app for reproducing minimal example

publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.2

  cupertino_icons: ^0.1.3

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

Answer

Hi you need to add networking permission to AndroidManifest.xml check this official documentation on flutter networking https://flutter.dev/docs/development/data-and-backend/networking

it is located in android/src/main/AndroidManifest.xml

<manifest xmlns:android...>
 ...
 <uses-permission android:name="android.permission.INTERNET" />
 <application ...
</manifest>
Categories
discuss

What is meant by {Author_name}* (with asterisk) in Version Control “Log” window of Android Studio?

I am working on a project with one of my teammates. Today I just observed a very strange thing which is this *(Asterisk) with the Author Name in version control of the Android Studio Log window.

Normally I take the things related to git or version control seriously
so after merging I double-checked the changes of that
*(Asterisk) commit and the changes were there after merging. So
technically there is nothing wrong with the code and everything seems
perfect.

But still, if anyone knows what this *(Asterisk) means I would love to hear your thoughts?

Thanks in advance 🙂

Android studio VCS Log window screenshot

Answer

It means that the author and commiter are different. Can happen, for example, if A cherry-pick’s B’s commits, or if A rebases a branch containing commits by B.

In the commit description (in the lower right) you should see, below the message and author, something like “Commited by XXXX”.

Categories
discuss

Vuetify multiple v-select required rules don’t work

Steps to reproduce:

If its multiple select required rules don’t work if its not a multiple its ok.

Expected Behavior

rules to work for multiple select as well

Actual Behavior

rules don’t work if its multiple select

Reproduction code :

 <div id="app">
     <v-app id="inspire">
      <v-select
         :items="role"
         label="Admin level*"
         class="mt-3 "
         @focus="reset"
         item-text="name"
         item-value="name"
         v-model="roleee"
         required
         :rules="rules.select"
      ></v-select>
      <v-select
         :items="subsidiaries"
         label="Subsidiary*"
         class="mt-3 "
         @focus="reset"
         item-text="name"
         item-value="name"            
         v-model="subsidiariesss"
         multiple
         required
         :rules="rules.select"
         :menu-props="{ bottom: true, offsetY: true }"
       ></v-select>
      </v-app>
     </div>
     <script>
        new Vue({
        el: '#app',
        data: {
         role:[
          {name:'Admin', id:1},
          {name: 'SuperAdmin', id:2}
          ], 
          subsidiaries: [
           {name: "ASdsad", id:1},
           {name: "dsd", id:2},
           {name: "34", id:3},
           {name: "ASvxcdsad", id:4}
          ],
          rules: {
           select: [v => !!v || 'Item is required'] 
          }
          },
        methods: {
         reset() {
          this.$refs.form.resetValidation();
         },
        }
       })
      </script>

Answer

You should add another rule called select2 which verifies the length of selected items :

 rules: {
      select: [(v) => !!v || "Item is required"],
      select2: [(v) =>  v.length>0 || "Item is required in select 2"],
      
    }

then bind it to the second select as follows :

 <v-select
         :items="subsidiaries"
         label="Subsidiary*"
         class="mt-3 "
         @focus="reset"
         item-text="name"
         item-value="name"            
         v-model="subsidiariesss"
         multiple
         required
         :rules="rules.select2"
         :menu-props="{ bottom: true, offsetY: true }"
       ></v-select>

LIVE DEMO

Categories
discuss

Is being covered by another element Cypress

Timed out retrying: cy.select() failed because this element:

<select aria-describedby="searchDropdownDescription" class="nav-search-dropdown searchSelect" data-nav-digest="Xa0GQ+pPQ/tdsV+GmRWeXB8PUD0=" data-nav-selected="0" id="searchDropdownBox" name="url" style="display: block;" tabindex="0" title="Search in">...</select>

is being covered by another element:

<input type="text" id="twotabsearchtextbox" value="" name="field-keywords" autocomplete="off" placeholder="" class="nav-input" dir="auto" tabindex="0" aria-label="Search">

Fix this problem, or use {force: true} to disable error checking. My code:

describe('Amazon test', function()
{
    it('Matching book', function()
    {
        cy.visit("https://amazon.com")
        cy.title().should('eq',"Amazon.com: Online Shopping for Electronics, Apparel, Computers, Books, DVDs & more")
        cy.get('#twotabsearchtextbox').click({force: true}).get('#searchDropdownBox').select('Books')
        
    })
  })

How can I resolve it?

Answer

Try this:

cy.get('#twotabsearchtextbox').click().get('#searchDropdownBox').select('Books',{force: true})
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..